具有某些已知和某些未知属性名称的对象的Typescript接口
我有一个对象,其中所有键都是string,一些值是string,其余是以下形式的对象:具有某些已知和某些未知属性名称的对象的Typescript接口,typescript,Typescript,我有一个对象,其中所有键都是string,一些值是string,其余是以下形式的对象: var object = { "fixedKey1": "something1", "fixedKey2": "something2", "unknownKey1": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'}, "unknownKey2": { 'param1': [1,2,3], 'param2':
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'},
...
...
};
在该对象中,fixedKey1
和fixedKey2
是该对象中的已知键<代码>未知项-值对可以从1到n不等
我尝试将对象的接口定义为:
interface IfcObject {
[keys: string]: {
param1: number[];
param2: string;
param3: string;
}
}
但这会引发以下错误:
类型编号的变量不可分配给类型对象
我发现它无法将此接口分配给“fixedKey-value”对
那么,我如何对这类变量进行类型检查呢?这不是您想要的,但您可以使用: 同样,您可以使用union属性为相应的对象定义接口 我会说你应该为对象值定义一个接口,然后你应该定义你的原始对象 示例界面可以是:
export interface IfcObjectValues {
param1: number[];
param2: string;
param3: string;
}
export interface IfcMainObject {
[key : string]: string | IfcObjectValues;
}
这个问题的正确答案是:
export interface IfcObjectValues {
param1: number[];
param2: string;
param3: string;
}
interface MyInterface {
fixedKey1: string,
fixedKey2: number,
[x: string]: IfcObjectValues,
}
正在运行的代码。类型为“number”的属性“fixedKey2”不可分配给字符串索引类型“IfcObjectValues”。这发生在TypeScript 2.8.3中。除非将未知属性键入为
any
,否则此操作无效,除非将未知属性键入为unknown
export interface IfcObjectValues {
param1: number[];
param2: string;
param3: string;
}
interface MyInterface {
fixedKey1: string,
fixedKey2: number,
[x: string]: IfcObjectValues,
}