TypeScript Compiler API
getWidenedType()
Applies the checker widening operation to a semantic type. It is not a general literal-to-primitive conversion API: a literal type can remain a literal. Inference for mutable variable declarations is a separate context-dependent process. The example compares inferred types and the explicit widening query. Baseline: TypeScript 5.8.3 and Node.js. The example is a local tooling script in a disposable directory; it writes temporary project files, not a ByteMind CodeRunner exercise.
Formal Syntax & Structure
typescript syntaxtypescript
checker.getWidenedType(type: ts.Type): ts.TypeParameters & Attributes
| Name | Type | Description |
|---|---|---|
| type | ts.Type | Semantic type from the current checker. |
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 fs = require("node:fs");const path = require("node:path");function inspect(text, extra = {}) { fs.writeFileSync("main.ts", text); for (const [name, content] of Object.entries(extra)) fs.writeFileSync(name, content); const program = ts.createProgram([path.resolve("main.ts")], { strict: true, types: [], target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, noEmit: true }); assert.deepEqual(ts.getPreEmitDiagnostics(program).map(d => d.code), []); const source = program.getSourceFile(path.resolve("main.ts")); const checker = program.getTypeChecker(); function find(predicate) { function visit(node) { return predicate(node) ? node : ts.forEachChild(node, visit); } const node = visit(source); assert(node); return node; } function variable(name) { return find(n => ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.name.text === name); } return { source, checker, find, variable };}const {checker:c,variable}=inspect('const fixed="x"; let mutable="x";');const a=c.getTypeAtLocation(variable("fixed").name), b=c.getTypeAtLocation(variable("mutable").name);assert.equal(c.typeToString(a),'"x"'); assert.equal(c.typeToString(b),"string");assert.equal(c.typeToString(c.getWidenedType(a)),'"x"');assert.equal(c.typeToString(c.getWidenedType(b)),"string");console.log('const: "x"; let: string; widened const: "x"');
// Run: node example.cjs// Expected stdout: const: "x"; let: string; widened const: "x"