mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Narrow by comparisons to boolean literals (#53714)
This commit is contained in:
@@ -136,6 +136,7 @@ import {
|
||||
isBlock,
|
||||
isBlockOrCatchScoped,
|
||||
IsBlockScopedContainer,
|
||||
isBooleanLiteral,
|
||||
isCallExpression,
|
||||
isClassStaticBlockDeclaration,
|
||||
isConditionalTypeNode,
|
||||
@@ -1279,7 +1280,8 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
|
||||
case SyntaxKind.EqualsEqualsEqualsToken:
|
||||
case SyntaxKind.ExclamationEqualsEqualsToken:
|
||||
return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
|
||||
isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
|
||||
isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) ||
|
||||
(isBooleanLiteral(expr.right) && isNarrowingExpression(expr.left) || isBooleanLiteral(expr.left) && isNarrowingExpression(expr.right));
|
||||
case SyntaxKind.InstanceOfKeyword:
|
||||
return isNarrowableOperand(expr.left);
|
||||
case SyntaxKind.InKeyword:
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
BigIntLiteral,
|
||||
BigIntLiteralType,
|
||||
BinaryExpression,
|
||||
BinaryOperator,
|
||||
BinaryOperatorToken,
|
||||
binarySearch,
|
||||
BindableObjectDefinePropertyCall,
|
||||
@@ -44,6 +45,7 @@ import {
|
||||
BindingPattern,
|
||||
bindSourceFile,
|
||||
Block,
|
||||
BooleanLiteral,
|
||||
BreakOrContinueStatement,
|
||||
CallChain,
|
||||
CallExpression,
|
||||
@@ -27661,6 +27663,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
|
||||
return type;
|
||||
}
|
||||
|
||||
function narrowTypeByBooleanComparison(type: Type, expr: Expression, bool: BooleanLiteral, operator: BinaryOperator, assumeTrue: boolean): Type {
|
||||
assumeTrue = (assumeTrue !== (bool.kind === SyntaxKind.TrueKeyword)) !== (operator !== SyntaxKind.ExclamationEqualsEqualsToken && operator !== SyntaxKind.ExclamationEqualsToken);
|
||||
return narrowType(type, expr, assumeTrue);
|
||||
}
|
||||
|
||||
function narrowTypeByBinaryExpression(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type {
|
||||
switch (expr.operatorToken.kind) {
|
||||
case SyntaxKind.EqualsToken:
|
||||
@@ -27709,6 +27716,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
|
||||
if (isMatchingConstructorReference(right)) {
|
||||
return narrowTypeByConstructor(type, operator, left, assumeTrue);
|
||||
}
|
||||
if (isBooleanLiteral(right)) {
|
||||
return narrowTypeByBooleanComparison(type, left, right, operator, assumeTrue);
|
||||
}
|
||||
if (isBooleanLiteral(left)) {
|
||||
return narrowTypeByBooleanComparison(type, right, left, operator, assumeTrue);
|
||||
}
|
||||
break;
|
||||
case SyntaxKind.InstanceOfKeyword:
|
||||
return narrowTypeByInstanceof(type, expr, assumeTrue);
|
||||
|
||||
Reference in New Issue
Block a user