[英]Union type in object keys supresses errors in typescript
Lets have a function让我们有一个功能
type UnionType = 'option1' | 'option2'
const myFunction = (arg: Partial<Record<UnionType, number>>) => {
console.log(arg)
}
calling it with argument of wrong type用错误类型的参数调用它
myFunction({option1: 1, ['option3' as 'option3']: 2})
results in an error Argument of type '{ option1: number; option3: number; }' is not assignable to parameter of type 'Partial<Record<UnionType, number>>'. Object literal may only specify known properties, and '['option3' as 'option3']' does not exist in type 'Partial<Record<UnionType, number>>'
导致错误
Argument of type '{ option1: number; option3: number; }' is not assignable to parameter of type 'Partial<Record<UnionType, number>>'. Object literal may only specify known properties, and '['option3' as 'option3']' does not exist in type 'Partial<Record<UnionType, number>>'
Argument of type '{ option1: number; option3: number; }' is not assignable to parameter of type 'Partial<Record<UnionType, number>>'. Object literal may only specify known properties, and '['option3' as 'option3']' does not exist in type 'Partial<Record<UnionType, number>>'
This is expected.这是意料之中的。 However if we change the type of the
option3
argument to an union type, the error vanishes, which is unexpected.但是,如果我们将
option3
参数的类型更改为联合类型,错误就会消失,这是出乎意料的。 This raises no error:这不会引发错误:
myFunction({option1: 1, ['option3' as 'option3' | 'option4']: 2})
Why is that?这是为什么?
This is a current limitation or missing feature of TypeScript.这是 TypeScript 的当前限制或缺失功能。 Computed property keys whose types aren't single string literals get widened all the way to
string
and thus the object gets an index signature most people don't expect.类型不是单个字符串文字的计算属性键会一直扩展为
string
,因此对象会获得大多数人不期望的索引签名。
Observe the inferred type of your object literal:观察你的对象字面量的推断类型:
const v = { option1: 1, ['option3' as 'option3' | 'option4']: 2 };
/* const v: {
[x: string]: number;
option1: number;
} */
That means the compiler thinks that v
might have all kinds of property keys, all of which would have a number
value, and therefore v
is assignable to {option1?: number, option2?: number}
:这意味着编译器认为
v
可能具有各种属性键,所有这些属性键都有一个number
值,因此v
可以分配给{option1?: number, option2?: number}
:
myFunction(v); // okay
See microsoft/TypeScript#13948 and microsoft/TypeScript#38663 for more information and an authoritative source.有关更多信息和权威来源,请参阅microsoft/TypeScript#13948和microsoft/TypeScript#38663 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.