[英]Why doesn't TypeScript complain about incorrect values in Partial types with computed keys?
Why does TypeScript allow the following? 为什么TypeScript允许以下内容?
interface SubType {
key: keyof MyType
}
interface MyType {
a: string
b: string
}
const container: SubType = { key: 'a' }
const test: Partial<MyType> = {
[container.key]: 3
}
It correctly complains when key
isn't actually a key in MyType
, but it doesn't seem to care what I set the value to, even though MyType
can only have string
values. 当
key
实际上不是MyType
的键时,它会正确抱怨,但是即使MyType
只能具有string
值,它似乎也不在乎我将值设置为什么。
If the type of a computed property name is not a singleton (here the type of container.key
is "a" | "b"
), then TypeScript isn't smart enough to validate the value at all. 如果计算出的属性名称的类型不是单例(此处
container.key
的类型为"a" | "b"
),则TypeScript不够聪明,根本无法验证该值。 See the checkObjectLiteral
function in src/compiler/checker.ts
. 请参阅
src/compiler/checker.ts
的checkObjectLiteral
函数。 Note that if you comment out the b: string
member of MyType
, so that the type of container.key
becomes "a"
, then the expected error appears. 请注意,如果您注释掉
MyType
的b: string
成员,以便container.key
的类型变为"a"
,则会出现预期的错误。 There's a little more information in this issue report . 在此问题报告中还有更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.