typescript 如何在打字稿中定义对象类型的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39207048/
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 define Object of Objects type in typescript
提问by marius
I have an object to store cached data which should look like this:
我有一个对象来存储缓存数据,它应该是这样的:
private data = {
'some_thing': new DataModel(),
'another_name': new DataModel()
}
I'm trying to assign an empty object to it in the constructor:
我试图在构造函数中为其分配一个空对象:
this.data = {}; // produces build error
Basically, i need to define the type of "data" field to say that it's going to have keys with random names and values of type DataModel. I've tried to do this:
基本上,我需要定义“数据”字段的类型,以说明它将具有具有随机名称和 DataModel 类型值的键。我试过这样做:
private data: Object<DataModel>
But this is invalid. How would i specify a correct type?
但这是无效的。我将如何指定正确的类型?
回答by Nitzan Tomer
It should be:
它应该是:
private data: { [name: string]: DataModel };
And then this should work:
然后这应该有效:
this.data = {};