Closed
Description
Bug Report
With the strict null check turned on
function test(options?: { fields?: string , strict?: boolean}) {
options = Object.assign({ fields: null }, options);
if (options.fields) {
//^^^^^^^ Object is possibly 'undefined'.ts(2532)
}
const test2 = () => {
if (options.strict) {
//^^^^^^^ Object is possibly 'undefined'.ts(2532)
}
}
}
Any of the following changes fix the first (but not the second):
function test(options?: { fields?: string|null }) {
options = Object.assign({ fields: '' }, options);
options = Object.assign({ a:null }, options);
🔎 Search Terms
strictNullCheck, Object.assign
🕗 Version & Regression Information
4.1.3
⏯ Playground Link
💻 Code
🙁 Actual behavior
Wrongly assumes the options can be undefined
🙂 Expected behavior
Should be no error
Metadata
Metadata
Assignees
Labels
No labels
Activity
jcalz commentedon Mar 6, 2021
There's a number of issues mixed together here:
{fields: null}is not assignable to type{fields?: string}. Optional properties can beundefined, notnull. Is this a mistake?Object.assign()produces an intersection type, which is only an approximation of what happens when there is property overlap, see Bug Report + Proposal: Object.assign() #31982 for why.Object.assign()here,{fields: null} & ({ fields?: string , strict?: boolean} | undefined), will be reduced tonever. Apparently the reduction toneverhere makes the compiler forget about any control flow narrowing foroptions, and it resets to the original type ofoptions, which includesundefinedin its domain. When you make any of the changes you mention above, this reduction toneverdoesn't happen, because there's no longer an impossible discriminant type.This is a combination of things working as intended and known design limitations. If you think there's something here that isn't explained by the above points, could you point it out?
holdfenytolvaj commentedon Mar 6, 2021
Thanks for the detailed answer