【问题标题】:Typescript interface for objects with some known and some unknown property names具有一些已知和一些未知属性名称的对象的 Typescript 接口
【发布时间】:2016-11-10 15:41:59
【问题描述】:

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

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”对。

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这不是你想要的,但你可以使用union type

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

    它涵盖了您的情况。但未知属性的类型可能是string

    【讨论】:

      【解决方案2】:
      export interface IfcObjectValues {
          param1: number[];
          param2: string;
          param3: string;        
      }
      
      interface MyInterface {
        fixedKey1: string,
        fixedKey2: number,
        [x: string]: IfcObjectValues, 
      }
      

      您的代码正在运行,see here

      【讨论】:

      • “number”类型的属性“fixedKey2”不可分配给字符串索引类型“IfcObjectValues”。这发生在 TypeScript 2.8.3 中。
      • 这行不通,除非您将未知属性键入为any
      • 这行不通,除非您将未知属性键入为unknown
      • 这不是一个正确的答案,并且链接的游乐场没有反映这里发布的代码。
      【解决方案3】:

      作为@Paleo explained,您可以使用联合属性为您的相应对象定义一个接口。

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

      示例界面可以是:

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

      【讨论】:

        猜你喜欢
        • 2019-07-14
        • 1970-01-01
        • 1970-01-01
        • 2016-01-30
        • 2019-04-03
        • 2022-08-16
        • 2018-07-04
        • 2021-10-21
        相关资源
        最近更新 更多