Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: incorrect type for object spread operator?

Tags:

typescript

Consider this code snippet:

type Foo = {
  x: string;
  y: number;
};

let a: Foo = {
  x: "@",
  y: 3,
};

let b: Partial<Foo> = { x: "#", y: undefined };

let c = { ...a, ...b };

Clearly type of c cannot be Foo because property y is undefined: runtime value of c is {x: "#", y: undefined} (at least in Chrome). Yet Typescript infers c type as { x: string; y: number;}. You can check in https://www.typescriptlang.org/play for version 4.0.5. I'm confused.

EDIT: here is the link from the comments to the github issue with the exact same problem https://github.com/microsoft/TypeScript/issues/13195#issuecomment-373178677 . For now this is the answer.

like image 915
Matrix Norm Avatar asked Nov 07 '22 04:11

Matrix Norm


1 Answers

The main issue there is the type Partial<Foo>:

let b: Partial<Foo> = { x: "#", y: undefined };

When you specify the variable type, the ts compiler usually ignores the right side of the assignment and doesn't use it for type inference (there are some exceptions, but in general it works this way).

like image 186
anstarovoyt Avatar answered Nov 15 '22 11:11

anstarovoyt