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.FunctionDeclaration

Parameters & Attributes

NameTypeDescription
modifiersreadonly ts.ModifierLike[] | undefinedModifiers or undefined.
asteriskTokents.AsteriskToken | undefinedGenerator marker or undefined.
namestring | ts.Identifier | undefinedFunction name or undefined.
typeParametersreadonly ts.TypeParameterDeclaration[] | undefinedGeneric parameters or undefined.
parametersreadonly ts.ParameterDeclaration[]Function parameters.
typets.TypeNode | undefinedReturn annotation or undefined.
bodyts.Block | undefinedFunction 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;// }
TypeScript Reference