简体   繁体   中英

Why doesn't TypeScript complain about incorrect values in Partial types with computed keys?

Why does TypeScript allow the following?

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.

Link to 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. See the checkObjectLiteral function in src/compiler/checker.ts . 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. There's a little more information in this issue report .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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