【问题标题】:How to define the type for the value of an object property如何定义对象属性值的类型
【发布时间】:2020-11-04 19:58:05
【问题描述】:

在 TypeScript 中,我可以如下声明一个类型化数组:

interface Something {
  a: number,
  b: number
}

const arr: Array<Something> = [{a:1, b:2}, {a:3, b:4}]

但是我将如何声明对象等价物的类型:

const obj = {
  propA: {a:1, b:2},
  propB: {a:3, b:4}
}

在这里,我不关心 propA、propB 等的名称,我不想要定义顶级属性名称的接口,但我确实想强制每个属性值的类型为 Something .这可能吗?提前致谢。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你可以使用{ [key: string]: Something }:

    const obj: { [key: string]: Something } = {
      propA: {a:1, b:2},
      propB: {a:3, b:4}
    }
    

    playground.

    【讨论】:

    • 传奇,非常感谢 - 只要允许我就会接受
    【解决方案2】:

    @Psidom 已正确回答。归功于他。我只是在回答,因为上面回答的代码可以通过定义自定义对象的另一个接口来模块化。

    interface myJsonObject{
     [key: string] : Something
    }
    
    const obj: myJsonObject = {
     propsA : {a: 1, b:2},
     propsB : {a: 3, b:4}
    }
    

    当您想在另一个打字稿文件中使用相同的 myJsonObject 时,这可能会对您有所帮助。您可以在*.d.ts 中添加此接口,然后将其导出并导入到任何 typescript 文件中。

    //my.d.ts
    interface Something {
      a: number,
      b: number
    }
    export interface myJsonObject {
      [key: string] : Something
    }
    
    //any_typescript_file.ts
    import { myJsonObject } from "./my.d.ts"
    
    const obj: myJsonObject = {
     propsA : {a: 1, b:2},
     propsB : {a: 3, b:4}
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2021-12-16
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      相关资源
      最近更新 更多