如何在 TypeScript 中做动态对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30840596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do dynamic objects in TypeScript
提问by gevik
Is there any way to define a dynamic object type in TypeScript? In the following example, I would like to define a type for "My Complex Type" by saying:
有没有办法在 TypeScript 中定义动态对象类型?在以下示例中,我想通过以下方式为“我的复杂类型”定义一个类型:
Objects of type "My Complex Type" are objects having "any number of properties" but the values of those properties must be of type IValue.
“我的复杂类型”类型的对象是具有“任意数量的属性”的对象,但这些属性的值必须是 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
}
回答by Slawek
Yes, that kind of behavior can be achieved, but in slightly different way. You just need to use typescript interface, like:
是的,可以实现这种行为,但方式略有不同。您只需要使用 typescript 接口,例如:
interface IValue {
prop: string
}
interface MyType {
[name: string]: IValue;
}
that will be used for example like:
这将用于例如:
var t: MyType = {};
t['field1'] = { prop: null };
t['field2'] = new DifferentType(); // compile-time error
...
var val = t['field1'];
val.prop = 'my prop value';
You don't have to create typescript class, Everything you need is a regular javascript object ( in that case {} ) and make it implement interface MyType, so it behaves like dictionary and provide you with compile-time type safety.
您不必创建 typescript 类,您需要的一切都是一个常规的 javascript 对象(在这种情况下为 {} )并使其实现接口 MyType,因此它的行为类似于字典并为您提供编译时类型安全。