gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:28:18 24 4
gpt4 key购买 nike

如果我想在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com