Typescript 使用字符串访问属性

Typescript 使用字符串访问属性,typescript,Typescript,使用字符串访问接口/类属性的正确方法是什么 我有以下界面 interface Type { nestedProperty: { a: number b: number } } 我想使用数组迭代设置嵌套属性,如下所示: let myType:Type = ... ["a", "b"].forEach(attributeName => myType.nestedProperty[attributeName] = 123) TS抱怨“nestedProperty”没有

使用字符串访问接口/类属性的正确方法是什么

我有以下界面

interface Type {
  nestedProperty: {
    a: number
    b: number
  }
}
我想使用数组迭代设置嵌套属性,如下所示:

let myType:Type = ...
["a", "b"].forEach(attributeName => myType.nestedProperty[attributeName] = 123)
TS抱怨“nestedProperty”没有字符串索引类型。如果我添加If-typeguard(例如,
If(attributeName==“a”)
编译器很高兴,但我真的不想去
If(…==…| |…==…| |…){
路由

我也不想使用索引类型:

interface Type<T> {
  [index:string]: <T>
  a: <T>
  b: <T>
}

您必须明确地告诉TypeScript,您使用的数组只包含
nestedProperty
属性中允许作为键的属性

interface Type {
  nestedProperty: {
    a: number
    b: number
  }
}

// Create a type alias for convenience. The type itself
// is a list of keys allowed in the `nestedProperty`.
type NestedAccessors = Array<keyof Type['nestedProperty']>

// Now TS is happy to do anything with the list since it
// can guarantee you're using proper values.
(["a", "b"] as NestedAccessors).forEach(attributeName => myType.nestedProperty[attributeName] = 123)
接口类型{
嵌套属性:{
a:号码
b:号码
}
}
//为方便起见,请创建类型别名。类型本身
//是“nestedProperty”中允许的键列表。
类型NestedAccessors=Array
//现在TS很乐意对列表做任何事情,因为它
//可以保证您使用的是正确的值。
([“a”,“b”]作为NestedAccessor).forEach(attributeName=>myType.nestedProperty[attributeName]=123)
我会选择:

接口类型{
nestedProperty:{[输入('a'|'b')]:编号}
}
让myType:Type={
嵌套属性:{
答:1,,
b:2,
}
};
([“a”,“b”]作为数组).forEach(attributeName=>myType.nestedProperty[attributeName]=123)

考虑到这个问题,如果你不想声明一个额外的类型,这可能是一种方法。但是我喜欢更明确地声明的东西,就像在接受的答案中一样。

我不确定你的
类型
接口是否只是一个普通的例子。如果不是,你可以使用
接口类型{nestedProperty:{[key:string]:number};}
是的。这是“解决方案”之一,但我不希望
Type
成为动态结构,我可以在其中放置任何东西。我想坚持使用一组已定义的属性。我对问题进行了更精确的编辑,那么
接口类型{nestedProperty:{[key in('a''b')]:number};}
keyof
!还没有在文档中看到过:)看起来真的很干净。非常感谢。到目前为止,键入脚本已经有几天了。完全沉浸在爱中。现在更多:)作为后续:有没有办法将NestedAccessor转换为数组,这样我就可以使用
NestedAccessorSomeHowturnedintoArray.forEach(accessor=>…)
?将应用程序编译为JavaScript后,您无法在运行时访问接口。您能做的最好的事情是访问实现类型接口的现有对象的属性。
const arr=object.keys(myType.nestedProperty)作为nestedAccessor将获得键值,然后您可以执行
arr.forEach(…)
。感谢您展示了一些额外的“类型乐趣”:)在访问期间强制转换看起来也不错:
myType.nestedProperty[attributeName as keyof type['nestedProperty']]=…
interface Type {
  nestedProperty: {
    a: number
    b: number
  }
}

// Create a type alias for convenience. The type itself
// is a list of keys allowed in the `nestedProperty`.
type NestedAccessors = Array<keyof Type['nestedProperty']>

// Now TS is happy to do anything with the list since it
// can guarantee you're using proper values.
(["a", "b"] as NestedAccessors).forEach(attributeName => myType.nestedProperty[attributeName] = 123)