From 8528dbee763e096e6cec72b38e5014b1ffb9ffd0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 21 May 2018 16:17:56 -0700 Subject: [PATCH] Handle union types in getRegularTypeOfLiteralType --- src/compiler/checker.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fb2e2ba3413..c36e5075a0e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9286,8 +9286,10 @@ namespace ts { return type; } - function getRegularTypeOfLiteralType(type: Type) { - return type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral ? (type).regularType : type; + function getRegularTypeOfLiteralType(type: Type): Type { + return type.flags & TypeFlags.StringOrNumberLiteral && type.flags & TypeFlags.FreshLiteral ? (type).regularType : + type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value: string | number, enumId?: number, symbol?: Symbol) { @@ -12774,11 +12776,11 @@ namespace ts { // all inferences were made to top-level occurrences of the type parameter, and // the type parameter has no constraint or its constraint includes no primitive or literal types, and // the type parameter was fixed during inference or does not occur at top-level in the return type. - const widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + const primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + const widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - const baseCandidates = widenLiteralTypes ? sameMap(candidates, getWidenedLiteralType) : - hasPrimitiveConstraint(inference.typeParameter) ? sameMap(candidates, getRegularTypeOfLiteralType) : + const baseCandidates = primitiveConstraint ? sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? sameMap(candidates, getWidenedLiteralType) : candidates; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a