CodeIntern
CodeIntern

Reputation: 1468

Typescript won't give an error when I'm destructuring a Partial type after destructuring the original type

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

Answers (1)

Jonas Wilms
Jonas Wilms

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

Related Questions