Narrow by clause expressions in switches with true condition (#53681)

This commit is contained in:
Mateusz Burzyński
2023-09-18 21:07:17 +02:00
committed by GitHub
parent 686cb1b63c
commit 70b7de11fb
5 changed files with 366 additions and 1 deletions

View File

@@ -1680,7 +1680,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
function bindCaseBlock(node: CaseBlock): void {
const clauses = node.clauses;
const isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
const isNarrowingSwitch = node.parent.expression.kind === SyntaxKind.TrueKeyword || isNarrowingExpression(node.parent.expression);
let fallthroughFlow = unreachableFlow;
for (let i = 0; i < clauses.length; i++) {
const clauseStart = i;

View File

@@ -27342,6 +27342,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, (expr as TypeOfExpression).expression)) {
type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
}
else if (expr.kind === SyntaxKind.TrueKeyword) {
const clause = flow.switchStatement.caseBlock.clauses.find((_, index) => index === flow.clauseStart);
const clauseExpression = clause && clause.kind === SyntaxKind.CaseClause ? clause.expression : undefined;
if (clauseExpression) {
type = narrowType(type, clauseExpression, /*assumeTrue*/ true);
}
}
else {
if (strictNullChecks) {
if (optionalChainContainsReference(expr, reference)) {