gpt4 book ai didi

typescript - 如何在 TypeScript 中做动态对象

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

有什么方法可以在 TypeScript 中定义动态对象类型吗?在下面的示例中,我想通过以下方式为“我的复杂类型”定义一个类型:

“我的复杂类型”类型的对象是具有“任意数量的属性”的对象,但这些属性的值必须是 IValue 类型。

// value interface
interface IValue {
prop:string
}

// My Complex Type
myType = {
field1:IValue
field2:IValue
.
.
.
fieldN:IValue
}

// Using My Complex Type

interface SomeType {
prop:My Complex Type
}

最佳答案

是的,这种行为是可以实现的,但方式略有不同。你只需要使用 typescript 接口(interface),比如:

interface IValue {
prop: string
}

interface MyType {
[name: string]: IValue;
}

这将用于例如:

var t: MyType = {};
t['field1'] = { prop: null };
t['field2'] = new DifferentType(); // compile-time error
...
var val = t['field1'];
val.prop = 'my prop value';

您不必创建 typescript 类,您需要的只是一个常规的 javascript 对象(在这种情况下为 {} )并使其实现接口(interface) MyType,因此它的行为类似于字典并为您提供编译时类型安全。

关于typescript - 如何在 TypeScript 中做动态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30840596/

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