typescript - 如何在 TypeScript 中为对象动态分配属性?

标签 typescript

如果我想在 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 that Record<Keys,Type> is a named alias to {[k: Keys]: Type} where Keys and Type 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/

相关文章:

嵌套类型的 typescript 联合会丢失类型之间不共享的 key

angular - 将数据从模态返回到 Angular 中的组件

javascript - 如何使用 libphonenumber AsYouTypeFormatter 处理退格键

typescript - 指定参数类型为 T |为空但不为空

angular - 如何调试 Angular 2 源代码 typescript 文件

css - 如何将 'required field' 星号添加到 Angular react 形式输入

typescript - 使用 Typescript 枚举值创建新类型

javascript - 如何从 json.stringify : ionic 读取特定值

arrays - Angular 5,来自 API 的 JSON 数组

typescript - 在 TypeScript 中引用外部模块