From 33985b24b7eb6b00ca256025f445addb9db67066 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 24 Mar 2016 06:50:01 -0700 Subject: [PATCH] Adding a few optimizations --- src/compiler/checker.ts | 10 +++++----- src/compiler/types.ts | 1 + 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index da5cc90caa4..7540482183d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7231,7 +7231,7 @@ namespace ts { } function getAssignmentReducedType(type: Type, assignedType: Type) { - if (type.flags & TypeFlags.Union) { + if (type !== assignedType && type.flags & TypeFlags.Union) { const reducedTypes = filter((type).types, t => isTypeAssignableTo(assignedType, t)); if (reducedTypes.length) { return reducedTypes.length === 1 ? reducedTypes[0] : getUnionType(reducedTypes); @@ -7241,10 +7241,7 @@ namespace ts { } function getNarrowedTypeOfReference(type: Type, reference: Node) { - if (!(type.flags & (TypeFlags.Any | TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter))) { - return type; - } - if (!isNarrowableReference(reference)) { + if (!(type.flags & TypeFlags.Narrowable) || !isNarrowableReference(reference)) { return type; } const leftmostNode = getLeftmostIdentifierOrThis(reference); @@ -7721,6 +7718,9 @@ namespace ts { const defaultsToDeclaredType = !strictNullChecks || !declaration || declaration.kind === SyntaxKind.Parameter || isInAmbientContext(declaration) || getContainingFunction(declaration) !== getContainingFunction(node); + if (defaultsToDeclaredType && !(type.flags & TypeFlags.Narrowable)) { + return type; + } const flowType = getFlowTypeOfReference(node, type, defaultsToDeclaredType ? type : undefinedType); if (strictNullChecks && !(type.flags & TypeFlags.Any) && !(getNullableKind(type) & TypeFlags.Undefined) && getNullableKind(flowType) & TypeFlags.Undefined) { error(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index c850fe47012..ed82d65d5dd 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2176,6 +2176,7 @@ namespace ts { ObjectType = Class | Interface | Reference | Tuple | Anonymous, UnionOrIntersection = Union | Intersection, StructuredType = ObjectType | Union | Intersection, + Narrowable = Any | ObjectType | Union | TypeParameter, /* @internal */ RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral, /* @internal */