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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With