From 2e0d0fcb6c0651bb88038849ac52105ae8e4bf3c Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 30 Jul 2024 09:30:01 -0700 Subject: [PATCH] Allow references to const variables with literal types in constant expressions --- src/compiler/checker.ts | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2578ba4c4df..4d446b6d0fe 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -46726,17 +46726,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (isConstantVariable(symbol)) { const declaration = symbol.valueDeclaration; - if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) { - const result = evaluate(declaration.initializer, declaration); - if (location && getSourceFileOfNode(location) !== getSourceFileOfNode(declaration)) { - return evaluatorResult( - result.value, - /*isSyntacticallyString*/ false, - /*resolvedOtherFiles*/ true, - /*hasExternalReferences*/ true, - ); + if (declaration && isVariableDeclaration(declaration)) { + if (!declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) { + const result = evaluate(declaration.initializer, declaration); + return location && getSourceFileOfNode(location) !== getSourceFileOfNode(declaration) ? + evaluatorResult(result.value, /*isSyntacticallyString*/ false, /*resolvedOtherFiles*/ true, /*hasExternalReferences*/ true) : + evaluatorResult(result.value, result.isSyntacticallyString, result.resolvedOtherFiles, /*hasExternalReferences*/ true); + } + if (declaration.type && declaration.type.kind === SyntaxKind.LiteralType) { + const type = getTypeOfSymbol(symbol); + if (type.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { + return evaluatorResult((type as LiteralType).value as string | number); + } } - return evaluatorResult(result.value, result.isSyntacticallyString, result.resolvedOtherFiles, /*hasExternalReferences*/ true); } } return evaluatorResult(/*value*/ undefined);