Reputation: 1468
Given this scenario:
interface TEST {
somename: string;
somenum: number;
}
const partialTest: Partial<TEST> = {
somename: '',
somenum: undefined,
}
const test: TEST = {
somename: '',
somenum: 1,
}
const destructured: TEST = {
...test,
...partialTest,
}
console.log(destructured);
Why doesn't typescript give me an error saying that destructured
's somenum
property is undefined?
console.log
effectively shows that somenum
's value is undefined.
Upvotes: 0
Views: 287
Reputation: 138267
It's interesting. If you let typescript infer the types, it works correctly:
const partialTest = {
somename: '',
somenum: undefined
};
const destructured: TEST = { // error
...test,
...partialTest,
};
That is because on spreading undefined
over string
will result in undefined
which doesn't fit to TEST, while spreading string | undefined
over string
results in string
, which fits to TEST.
Unless there is no missing
type to distinguish between undefined
and "not-defined", this wont fix
Upvotes: 2