具有一些已知和一些未知属性名称的对象的 Typescript 接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38260414/
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
Typescript interface for objects with some known and some unknown property names
提问by yugantar kumar
I have an object where all the keys are string, some of the values are string and the rest are objects in this form:
我有一个对象,其中所有键都是字符串,一些值是字符串,其余是这种形式的对象:
var object = {
"fixedKey1": "something1",
"fixedKey2": "something2",
"unknownKey1": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'},
"unknownKey2": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'},
"unknownKey3": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'},
...
...
};
In this object fixedKey1
and fixedKey2
are the known keys which will be there in that object. unknownKey
- value pair can vary from 1-n.
在这个对象中fixedKey1
和fixedKey2
是该对象中将存在的已知键。unknownKey
- 值对可以在 1-n 之间变化。
I tried defining the interface of the object as:
我尝试将对象的接口定义为:
interface IfcObject {
[keys: string]: {
param1: number[];
param2: string;
param3: string;
}
}
But this throws the following error:
但这会引发以下错误:
Variable of type number is not assignable of type object
类型编号的变量不可分配给类型对象
Which I found out that it is not able to assign this interface to "fixedKey - value" pair.
我发现它无法将此接口分配给“fixedKey - value”对。
So, how can I do the type checking of this kind of variables?
那么,如何对此类变量进行类型检查呢?
采纳答案by Paleo
It's not exactly what you want, but you can use an union type:
这不完全是您想要的,但您可以使用联合类型:
interface IfcObject {
[key: string]: string | {
param1: number[];
param2: string;
param3: string;
}
}
回答by bersling
回答by Ajay
As @Paleo explained you can use union property to define an interface for your corresponding object.
正如@Paleo 所解释的,您可以使用 union 属性为相应的对象定义接口。
I would say you should define an interface for object values and then you should define your original object.
我会说你应该为对象值定义一个接口,然后你应该定义你的原始对象。
sample Interface can be
示例界面可以是
export interface IfcObjectValues {
param1: number[];
param2: string;
param3: string;
}
export interface IfcMainObject {
[key : string]: string | IfcObjectValues;
}