Closed
Description
TypeScript Version: 3.8.3 and nightly (tested on Playground as of May 4, 2020)
Search Terms: boolean constructor overload, constructor overload resolution
Code
class A { }
class B {
_x: boolean;
_y: boolean;
constructor(x: boolean, y: boolean);
constructor(a: A);
constructor(xOrA: A | boolean, y?: boolean) {
if (xOrA instanceof A) {
this._x = true;
this._y = true;
} else {
this._x = xOrA;
this._y = y;
}
}
}
Expected behavior: I expect this code to compile.
Actual behavior: Compilation failure on line this._y = y;
with error:
Type 'boolean | undefined' is not assignable to type 'boolean'.
Type 'undefined' is not assignable to type 'boolean'.(2322)
My understanding is that in the else branch of the if, the compiler knows that we are using the first overload, and therefore should be able to infer that y
must be defined. Maybe I missed something trivial, but after searching in the documentation and online I did not find any useful hint, so I am reporting the issue.
Related Issues: none found
Compiler Options
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"useDefineForClassFields": false,
"alwaysStrict": true,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"downlevelIteration": false,
"noEmitHelpers": false,
"noLib": false,
"noStrictGenericChecks": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"esModuleInterop": true,
"preserveConstEnums": false,
"removeComments": false,
"skipLibCheck": false,
"checkJs": false,
"allowJs": false,
"declaration": true,
"experimentalDecorators": false,
"emitDecoratorMetadata": false,
"target": "ES2017",
"module": "ESNext"
}
}
Playground Link: Provided