microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.69k stars 12.44k forks source link

Computed properties do not type check when they could #18596

Closed leoasis closed 7 years ago

leoasis commented 7 years ago

TypeScript Version: 2.4.2

Code

type A = { a: number, b: string };

const a: A = { a: 1, b: 'foo' };

const b: A = { ...a, b: 123 }; // doesn't type check, b should be string (correct)

const propB: 'b' = 'b';
const c: A = { ...a, [propB]: 123 }; // type checks even though i'm setting b to a number (incorrect)

Expected behavior:

Last statement should be invalid, since propB is of type 'b', which should be enough information for TS to know that i'm setting the b property.

Actual behavior:

Last statement is valid for TS. This also happens for union types of string or number literals. When the types for the values in those keys are the same, and attempting to set a value using a computed property, TS allows invalid values.

ghost commented 7 years ago

Looks like this was fixed by #18317. In typescript@next your last line is an error.

mhegazy commented 7 years ago

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.