简体   繁体   English

为什么TypeScript不抱怨带有计算键的Partial类型中的值不正确?

[英]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值,它似乎也不在乎我将值设置为什么。

Link to TS playrground 链接到TS Playrground

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.tscheckObjectLiteral函数。 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. 请注意,如果您注释掉MyTypeb: string成员,以便container.key的类型变为"a" ,则会出现预期的错误。 There's a little more information in this issue report . 此问题报告中还有更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM