TypeScript Compiler API
TypeChecker.getTypeAtLocation()
Returns the checker type associated with a program node. For expression uses, control-flow narrowing can change the result at different locations. An annotation, declaration and use may have distinct types; select the node that answers your analysis question. Baseline: the Node.js API of TypeScript 5.8.3. The examples are CommonJS tooling scripts, not browser or CodeRunner snippets. TypeScript must be installed locally.
Formal Syntax & Structure
typescript syntaxtypescript
checker.getTypeAtLocation(node: ts.Node): ts.TypeParameters & Attributes
| Name | Type | Description |
|---|---|---|
| node | ts.Node | A node from the same Program. |
Working Example
Example Snippettypescript
// Use a new empty directory. Install: npm install --save-exact typescript@5.8.3// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const options = { strict: true, types: [], target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS };const program = ts.createProgram(["input.ts"], options);const checker = program.getTypeChecker();const source = program.getSourceFile("input.ts");const observed = [];function visit(node) { if (ts.isCallExpression(node) && node.expression.getText(source) === "take") { observed.push(checker.typeToString(checker.getTypeAtLocation(node.arguments[0]))); } ts.forEachChild(node, visit);}visit(source);assert.deepEqual(observed, ["string | number", "string"]);console.log(observed.join(" -> "));
// File: input.ts (omit this label)declare function take(value: unknown): void;function test(value: string | number) { take(value); if (typeof value === "string") take(value); }
// Run: node example.cjs// Expected stdout: string | number -> string