【发布时间】:2020-11-12 08:43:21
【问题描述】:
运行以下 TypeScript 代码时:
type valueType = {[key: string]: number} | {[key: string]: {[date: string]: number}} | {[key: string]: string;}
const myData1: valueType = {
"name": "Eduardo",
"city": "Miami",
"state": "FL",
"age": 22,
"progress": {"2018": 67, "2019": 76, "2020": 89}
}
TypeScript 抱怨该对象不能分配给 valueType 类型,尽管我明确告诉它在对象内部可以有不同的类型。在一个对象中允许多种不同类型的正确方法是什么?
这是我得到的警告:
Type '{ "name": string; "city": string; "state": string; "age": number; }' is not assignable to type 'valueType'.
Type '{ "name": string; "city": string; "state": string; "age": number; }' is not assignable to type '{ [key: string]: string; }'.
Property '"age"' is incompatible with index signature.
Type 'number' is not assignable to type 'string'.
谢谢!
【问题讨论】:
标签: javascript typescript object types