[英]Why does typescript complain about a computed property name?
Using typescript Version 3.7.5.使用 typescript 版本 3.7.5。 I have these two simple types and I would expect that either both of them compile or neither do.
我有这两种简单的类型,我希望它们要么编译要么都不编译。 However, typescript only complains about the second one.
但是,typescript 只抱怨第二个。 Why is the second type invalid, but the first isn't?
为什么第二种无效,但第一种无效?
// this works
type foo = {
[key in 'xxx']: number
}
// this does not
type bar = {
xxx: number
[key in 'xxx']: number
}
Here are the compiler messages:以下是编译器消息:
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)
See the code in action in the typescript playground .请参阅typescript 操场中的代码。
The first definition is a mapped type ( doc ), which binds key
, so you can use it in the right-hand side, eg:第一个定义是一个映射类型( doc ),它绑定了
key
,所以你可以在右边使用它,例如:
type foo = {
[key in 'xxx']: key
}
You cannot add properties to mapped types though.但是,您不能将属性添加到映射类型。 For example, for
例如,对于
type foo = {
[key in 'xxx']: key
xxx: number
}
TypeScript will show an error about an expected }
at the position of xxx
. TypeScript 将在
xxx
的 position 处显示有关预期}
的错误。
On the other hand,另一方面,
type bar = {
xxx: number
[key in 'xxx']: number
}
is a regular type literal, in which [key in 'xxx']: number
is a computed property, for which the restrictions mentioned in the first two error messages hold.是一个常规类型文字,其中
[key in 'xxx']: number
是一个计算属性,前两个错误消息中提到的限制适用。
The third error message comes from TypeScript interpreting in
as the regular expression-level in
.第三条错误消息来自 TypeScript 将
in
解释in
. You can see the same error here:您可以在此处看到相同的错误:
const error = key in 'xxx'
(and if you hover over key
in your second example, you'll also see a Cannot find name 'key'.
error) (如果您在第二个示例中使用 hover over
key
,您还会看到Cannot find name 'key'.
错误)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.