像这样的正确打字稿类型是什么
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
索引签名参数类型必须为string
或number
:
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 }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句