Skip to content

Commit fc85bc5

Browse files
committed
Use "best choice type" for || and ?: operators
1 parent 394dbbf commit fc85bc5

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

src/compiler/checker.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12896,6 +12896,14 @@ namespace ts {
1289612896
return (target.flags & TypeFlags.Nullable) !== 0 || isTypeComparableTo(source, target);
1289712897
}
1289812898

12899+
function getBestChoiceType(type1: Type, type2: Type): Type {
12900+
const firstAssignableToSecond = isTypeAssignableTo(type1, type2);
12901+
const secondAssignableToFirst = isTypeAssignableTo(type2, type1);
12902+
return secondAssignableToFirst && !firstAssignableToSecond ? type1 :
12903+
firstAssignableToSecond && !secondAssignableToFirst ? type2 :
12904+
getUnionType([type1, type2], /*subtypeReduction*/ true);
12905+
}
12906+
1289912907
function checkBinaryExpression(node: BinaryExpression, contextualMapper?: TypeMapper) {
1290012908
return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node);
1290112909
}
@@ -13039,7 +13047,7 @@ namespace ts {
1303913047
leftType;
1304013048
case SyntaxKind.BarBarToken:
1304113049
return getTypeFacts(leftType) & TypeFacts.Falsy ?
13042-
getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) :
13050+
getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) :
1304313051
leftType;
1304413052
case SyntaxKind.EqualsToken:
1304513053
checkAssignmentOperator(rightType);
@@ -13166,7 +13174,7 @@ namespace ts {
1316613174
checkExpression(node.condition);
1316713175
const type1 = checkExpression(node.whenTrue, contextualMapper);
1316813176
const type2 = checkExpression(node.whenFalse, contextualMapper);
13169-
return getUnionType([type1, type2], /*subtypeReduction*/ true);
13177+
return getBestChoiceType(type1, type2);
1317013178
}
1317113179

1317213180
function typeContainsLiteralFromEnum(type: Type, enumType: EnumType) {

0 commit comments

Comments
 (0)