简体   繁体   中英

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>>'

This is expected. However if we change the type of the option3 argument to an union type, the error vanishes, which is unexpected. 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. 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.

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} :

myFunction(v); // okay

See microsoft/TypeScript#13948 and microsoft/TypeScript#38663 for more information and an authoritative source.

Playground link to code

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