如果我想在 Javascript 中以编程方式将属性分配给对象,我会这样做:
var obj = {};
obj.prop = "value";
但在 TypeScript 中,这会产生错误:
The property 'prop' does not exist on value of type '{}'
我应该如何为 TypeScript 中的对象分配任何新属性?
最佳答案
索引类型
可以表示obj
作为any
,但这违背了使用 typescript 的全部目的。 obj = {}
暗示 obj
是一个 Object
.将其标记为 any
没有意义。为了实现所需的一致性,可以按如下方式定义接口(interface)。
interface LooseObject {
[key: string]: any
}
var obj: LooseObject = {};
或使其紧凑:
var obj: {[k: string]: any} = {};
LooseObject
可以接受以任何字符串作为键和 any
的字段输入值。
obj.prop = "value";
obj.prop2 = 88;
此解决方案的真正优点在于您可以在界面中包含类型安全字段。
interface MyType {
typesafeProp1?: number,
requiredProp1: string,
[key: string]: any
}
var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number
obj.prop = "value";
obj.prop2 = 88;
Record<Keys,Type>
实用类型
Update (August 2020): @transang brought this up in comments
Record<Keys,Type>
is a Utility type in typescript. It is a much cleaner alternative for key-value pairs where property-names are not known. It's worth noting thatRecord<Keys,Type>
is a named alias to{[k: Keys]: Type}
whereKeys
andType
are generics. IMO, this makes it worth mentioning here
为了比较,
var obj: {[k: string]: any} = {};
成为
var obj: Record<string,any> = {}
MyType
现在可以通过扩展记录类型来定义
interface MyType extends Record<string,any> {
typesafeProp1?: number,
requiredProp1: string,
}
While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.
关于typescript - 如何在 TypeScript 中为对象动态分配属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12710905/