【问题标题】:TS interface - Object with any properties [duplicate]TS 接口 - 具有任何属性的对象 [重复]
【发布时间】:2021-01-09 12:58:09
【问题描述】:

如何在 TypeScript 中为具有任何属性的对象定义接口?

interface Data {
  properties: Properties;
}

interface Properties {
  ...
}

【问题讨论】:

    标签: typescript interface properties


    【解决方案1】:

    具有任何属性的对象就像any。为什么要定义一个额外的接口? 一个原因可能是,您希望允许特定的值类型。然后你可以这样做:

    interface Properties {
      [key: string]: string|number|boolean;
    }
    

    【讨论】:

    • 如果我做properties: any;,那么它可以是任何东西,但我希望它是Object,具有任意数量的任何属性,或者具体来说它只是:数字|布尔值 |细绳。但是任何数量的这些属性。这在 TS 中可能吗?
    【解决方案2】:

    也许你正在寻找这个

    type Primitive = string | number | boolean
    interface Data {
      [key: string]: Primitive
    }
    
    const data1: Data = {
      a: 1,
      b: true,
      c: 'asd'
    }
    
    // you basically dont need `Data` interface, instead you can use `Record` as below
    const rec: Record<string, Primitive> = data1
    

    【讨论】:

    • 谢谢我正在寻找这个[key: string]:
    • 好的,所以我不知道什么是 TS 中的记录,bcs。我一直在寻找它。泰!
    • 这称为索引类型,更多信息在这里:typescriptlang.org/docs/handbook/…
    【解决方案3】:

    你想要Record&lt;&gt; 类型:

    interface Data {
      properties: Record<string, number|boolean|string>
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多