具有一些已知属性名称和一些未知属性名称的对象的Typescript接口

时间:2016-07-08 06:43:15

标签: typescript

我有一个对象,其中所有键都是字符串,一些值是字符串,其余的是这种形式的对象:

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'},
    ...
    ...
};

在此对象中,fixedKey1fixedKey2是该对象中的已知键。 unknownKey - 值对可以在1-n之间变化。

我尝试将对象的接口定义为:

interface IfcObject {
    [keys: string]: {
        param1: number[];
        param2: string; 
        param3: string;
  }
}

但是这会引发以下错误:

  

类型编号的变量不能分配类型对象

我发现它无法将此界面分配给" fixedKey - value"对。

那么,我该如何对这种变量进行类型检查?

3 个答案:

答案 0 :(得分:12)

这不完全是您想要的,但您可以使用union type

interface IfcObject {
    [key: string]: string | {
        param1: number[];
        param2: string; 
        param3: string;
    }
}

答案 1 :(得分:7)

此问题的正确答案是:

export interface IfcObjectValues {
    param1: number[];
    param2: string;
    param3: string;        
}

interface MyInterface {
  fixedKey1: string,
  fixedKey2: number,
  [x: string]: IfcObjectValues, 
}

您的代码,see here

答案 2 :(得分:4)

正如@Paleo解释的那样,您可以使用union属性为相应的对象定义接口。

我会说你应该为对象值定义一个接口,然后你应该定义你的原始对象。

示例界面可以

export interface IfcObjectValues {
    param1: number[];
    param2: string;
    param3: string;        
}

export interface IfcMainObject {
 [key : string]: string | IfcObjectValues;
}
相关问题