首页 > 解决方案 > 对象对象的 TypeScript 类型?

问题描述

什么是正确的打字稿类型

const test: MyType = {
  foo: { value: 1 },
  bar: { value: 2 }
}

就像是

type MyType {
  [key: any]: {
    value:number
  }
}

结果是

Object literal may only specify known properties, and 'foo' does not exist in type 

标签: typescript

解决方案


索引签名参数类型必须是stringnumber

type MyType = {
    [key: string]: { value: number; };
};

const test: MyType = {
    foo: { value: 1 },
    bar: { value: 2 }
};

或者,使用Record

const test: Record<string, { value: number }> = {
    foo: { value: 1 },
    bar: { value: 2 }
}

const test: Record<'foo' | 'bar', { value: number }> = {
    foo: { value: 1 },
    bar: { value: 2 }
}

推荐阅读