Skip to content

Commit 2b64731

Browse files
authored
Fix getTypeAtLocation for as const to not issue a diagnostic (#36741)
* Fix getTypeAtLocation for `as const` to not issue a diagnostic * use existing helpers for checks * Fix lint
1 parent 5410233 commit 2b64731

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/compiler/checker.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11337,6 +11337,11 @@ namespace ts {
1133711337
function getTypeFromTypeReference(node: TypeReferenceType): Type {
1133811338
const links = getNodeLinks(node);
1133911339
if (!links.resolvedType) {
11340+
// handle LS queries on the `const` in `x as const` by resolving to the type of `x`
11341+
if (isConstTypeReference(node) && isAssertionExpression(node.parent)) {
11342+
links.resolvedSymbol = unknownSymbol;
11343+
return links.resolvedType = checkExpressionCached(node.parent.expression);
11344+
}
1134011345
let symbol: Symbol | undefined;
1134111346
let type: Type | undefined;
1134211347
const meaning = SymbolFlags.Type;

src/testRunner/unittests/programApi.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,17 @@ namespace ts {
180180
});
181181

182182
describe("unittests:: programApi:: Program.getDiagnosticsProducingTypeChecker / Program.getSemanticDiagnostics", () => {
183+
it("does not produce errors on `as const` it would not normally produce on the command line", () => {
184+
const main = new documents.TextDocument("/main.ts", "0 as const");
185+
186+
const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [main], cwd: "/" });
187+
const program = createProgram(["/main.ts"], {}, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed }));
188+
const typeChecker = program.getDiagnosticsProducingTypeChecker();
189+
const sourceFile = program.getSourceFile("main.ts")!;
190+
typeChecker.getTypeAtLocation(((sourceFile.statements[0] as ExpressionStatement).expression as AsExpression).type);
191+
const diag = program.getSemanticDiagnostics();
192+
assert.isEmpty(diag);
193+
});
183194
it("getSymbolAtLocation does not cause additional error to be added on module resolution failure", () => {
184195
const main = new documents.TextDocument("/main.ts", "import \"./module\";");
185196
const mod = new documents.TextDocument("/module.d.ts", "declare const foo: any;");

0 commit comments

Comments
 (0)