TypeScript Compiler API
NodeFactory.createVariableDeclaration()
Creates a single variable declaration, not a complete statement. Wrap it in a declaration list and variable statement; the list flags determine const/let/var. A type annotation and initializer are syntax nodes and may disagree until checked in a new program. 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
factory.createVariableDeclaration(name, exclamationToken?, type?, initializer?): ts.VariableDeclarationParameters & Attributes
| Name | Type | Description |
|---|---|---|
| name | string | ts.BindingName | Identifier or binding pattern. |
| exclamationToken | ts.ExclamationToken | Definite-assignment assertion token. |
| type | ts.TypeNode | Optional type annotation. |
| initializer | ts.Expression | Optional initial value expression. |
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 source = ts.createSourceFile("input.ts", "const count: number = 7;", ts.ScriptTarget.ES2022, true);const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });const f = ts.factory;const decl = f.createVariableDeclaration("score", undefined, f.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), f.createNumericLiteral(9));const list = f.createVariableDeclarationList([decl], ts.NodeFlags.Const);const statement = f.createVariableStatement(undefined, list);assert(ts.isVariableStatement(statement));console.log(printer.printNode(ts.EmitHint.Unspecified, statement, source));
// Run: node example.cjs// Expected stdout: const score: number = 9;