TypeScript Compiler API
NodeFactory.createFunctionDeclaration()
Creates function declaration syntax with parameter nodes, optional type parameters, return type and body. Pass undefined for absent positional slots; the parameter array is required. A bodyless signature is not executable, and a syntactically built body is not guaranteed to satisfy its declared type. 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.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body): ts.FunctionDeclarationParameters & Attributes
| Name | Type | Description |
|---|---|---|
| modifiers | readonly ts.ModifierLike[] | undefined | Modifiers or undefined. |
| asteriskToken | ts.AsteriskToken | undefined | Generator marker or undefined. |
| name | string | ts.Identifier | undefined | Function name or undefined. |
| typeParameters | readonly ts.TypeParameterDeclaration[] | undefined | Generic parameters or undefined. |
| parameters | readonly ts.ParameterDeclaration[] | Function parameters. |
| type | ts.TypeNode | undefined | Return annotation or undefined. |
| body | ts.Block | undefined | Function body or undefined. |
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 number = f.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);const param = f.createParameterDeclaration(undefined, undefined, "n", undefined, number);const body = f.createBlock([f.createReturnStatement(f.createBinaryExpression(f.createIdentifier("n"), ts.SyntaxKind.AsteriskToken, f.createNumericLiteral(2)))], true);const fn = f.createFunctionDeclaration(undefined, undefined, "twice", undefined, [param], number, body);assert(ts.isFunctionDeclaration(fn));console.log(printer.printNode(ts.EmitHint.Unspecified, fn, source));
// Run: node example.cjs// Expected stdout: function twice(n: number): number {// return n * 2;// }