Destructuring assignment removes undefined from type when default value is given

This commit is contained in:
Nathan Shively-Sanders 2016-06-29 09:12:50 -07:00
parent 6be7d9caa6
commit c5e680c8be
5 changed files with 50 additions and 0 deletions

View File

@ -12544,6 +12544,12 @@ namespace ts {
if (exprOrAssignment.kind === SyntaxKind.ShorthandPropertyAssignment) {
const prop = <ShorthandPropertyAssignment>exprOrAssignment;
if (prop.objectAssignmentInitializer) {
// In strict null checking mode, if a default value of a non-undefined type is specified, remove
// undefined from the final type.
if (strictNullChecks &&
!(getCombinedTypeFlags(checkExpressionCached(prop.objectAssignmentInitializer)) & TypeFlags.Undefined)) {
sourceType = getTypeWithFacts(sourceType, TypeFacts.NEUndefined);
}
checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper);
}
target = (<ShorthandPropertyAssignment>exprOrAssignment).name;

View File

@ -0,0 +1,11 @@
//// [destructuringAssignmentWithDefault.ts]
const a: { x?: number } = { };
let x = 0;
({x = 1} = a);
//// [destructuringAssignmentWithDefault.js]
var a = {};
var x = 0;
(_a = a.x, x = _a === void 0 ? 1 : _a, a);
var _a;

View File

@ -0,0 +1,12 @@
=== tests/cases/compiler/destructuringAssignmentWithDefault.ts ===
const a: { x?: number } = { };
>a : Symbol(a, Decl(destructuringAssignmentWithDefault.ts, 0, 5))
>x : Symbol(x, Decl(destructuringAssignmentWithDefault.ts, 0, 10))
let x = 0;
>x : Symbol(x, Decl(destructuringAssignmentWithDefault.ts, 1, 3))
({x = 1} = a);
>x : Symbol(x, Decl(destructuringAssignmentWithDefault.ts, 2, 2))
>a : Symbol(a, Decl(destructuringAssignmentWithDefault.ts, 0, 5))

View File

@ -0,0 +1,17 @@
=== tests/cases/compiler/destructuringAssignmentWithDefault.ts ===
const a: { x?: number } = { };
>a : { x?: number | undefined; }
>x : number | undefined
>{ } : {}
let x = 0;
>x : number
>0 : number
({x = 1} = a);
>({x = 1} = a) : { x?: number | undefined; }
>{x = 1} = a : { x?: number | undefined; }
>{x = 1} : { x?: number; }
>x : number
>a : { x?: number | undefined; }

View File

@ -0,0 +1,4 @@
// @strictNullChecks: true
const a: { x?: number } = { };
let x = 0;
({x = 1} = a);