This page documents the public TypeScript compiler API exposed through the typescript npm package. It covers the primary programmatic entry points for invoking the compiler, inspecting ASTs, and performing semantic analysis. For information about the language service API (editor features like completions and refactorings), see Language Service. For details on tsserver and the JSON protocol used by editors, see Language Server.
The typescript package ships a single bundled module (lib/typescript.js) that exports everything under the ts namespace. The public surface is canonically defined in the generated declaration file at tests/baselines/reference/api/typescript.d.ts
The API has three main uses:
| Use Case | Primary Entry Points |
|---|---|
| Full compilation (type-check + emit) | createProgram, Program.emit |
| Single-file parsing only | createSourceFile |
| Single-file transpilation (no type-check) | transpileModule |
| Editor / tooling integration | createLanguageService |
The diagram below maps user-facing API calls to the internal compiler components they drive.
Diagram: Public API Entry Points to Internal Components
Sources: src/compiler/program.ts328-340 src/services/services.ts1-360 tests/baselines/reference/api/typescript.d.ts1-50
createProgramcreateProgram is the primary entry point for full compilations. It accepts either a list of root file names and options, or a CreateProgramOptions object.
createProgram(rootNames, options, host?, oldProgram?, configFileParsingDiagnostics?)
createProgram(options: CreateProgramOptions)
The returned Program object is the top-level handle for all subsequent operations. Its key methods are:
| Method | Description |
|---|---|
getSourceFiles() | Returns all SourceFile nodes in the program |
getSourceFile(fileName) | Looks up a specific SourceFile |
getTypeChecker() | Returns the TypeChecker for semantic queries |
emit(targetSourceFile?, writeFile?, ...) | Runs the emitter; returns EmitResult |
getSyntacticDiagnostics(sourceFile?) | Parse-level errors |
getSemanticDiagnostics(sourceFile?) | Type-level errors |
getDeclarationDiagnostics(sourceFile?) | Errors from .d.ts generation |
getCompilerOptions() | Returns the active CompilerOptions |
getRootFileNames() | Returns the initial root file list |
getResolvedModuleFromModuleSpecifier(...) | Module resolution result |
Sources: src/compiler/program.ts1-326 tests/baselines/reference/api/typescript.d.ts3200-3350
createSourceFilecreateSourceFile(
fileName: string,
sourceText: string,
languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions,
setParentNodes?: boolean,
scriptKind?: ScriptKind
): SourceFile
Parses a single source text string into a SourceFile AST node without creating a full Program. Useful for tooling that only needs the parse tree.
setParentNodes — if true, sets the parent pointer on every AST node (required for many utilities)scriptKind — controls parsing mode: TS, TSX, JS, JSX, JSON, etc.Sources: src/compiler/parser.ts1-440 tests/baselines/reference/api/typescript.d.ts3380-3400
transpileModuletranspileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput
Performs single-file TypeScript-to-JavaScript transpilation with no cross-file type checking. Significantly faster than createProgram for cases where semantic correctness is not needed. TranspileOptions accepts a compilerOptions object and an optional moduleName.
TranspileOutput contains:
outputText — the emitted JavaScript stringsourceMapText — optional source map JSON stringdiagnostics — any syntactic errors encounteredSources: tests/baselines/reference/api/typescript.d.ts3400-3430
createLanguageServicecreateLanguageService(
host: LanguageServiceHost,
documentRegistry?: DocumentRegistry,
syntaxOnlyOrLanguageServiceMode?: boolean | LanguageServiceMode
): LanguageService
Creates an editor-facing LanguageService instance backed by a caller-supplied LanguageServiceHost. The host provides file contents, compiler options, and file system access incrementally. See Language Service for a full treatment of LanguageService capabilities.
Sources: src/services/services.ts1-360 src/services/types.ts1-100
CompilerHost InterfaceCompilerHost is the file system and environment abstraction used by createProgram. Callers can supply a custom host to redirect file I/O (e.g. for in-memory compilation or virtual file systems).
Key required methods:
| Method | Description |
|---|---|
fileExists(fileName) | Check if a file exists |
readFile(fileName) | Read file contents as a string |
getSourceFile(fileName, languageVersion, ...) | Parse and return a SourceFile |
getDefaultLibFileName(options) | Path to the default library (lib.d.ts) |
writeFile(fileName, data, ...) | Write output files |
getCurrentDirectory() | Current working directory |
getCanonicalFileName(fileName) | Normalize file name casing |
useCaseSensitiveFileNames() | Whether file names are case-sensitive |
getNewLine() | Line ending string |
A default host for Node.js is available via createCompilerHost(options).
Sources: src/compiler/types.ts5500-5600 tests/baselines/reference/api/typescript.d.ts3300-3380
Program Object and Compilation FlowDiagram: Program Lifecycle and Internal Calls
Sources: src/compiler/program.ts1-326 src/compiler/binder.ts1-310 src/compiler/checker.ts1-1155 src/compiler/emitter.ts1-430
SourceFileA SourceFile is the root AST node for a single file. Key properties:
| Property | Type | Description |
|---|---|---|
fileName | string | Absolute file path |
text | string | Full source text |
statements | NodeArray<Statement> | Top-level statements |
languageVersion | ScriptTarget | Target script version |
scriptKind | ScriptKind | JS/TS/JSX variant |
isDeclarationFile | boolean | Whether this is a .d.ts file |
referencedFiles | FileReference[] | Triple-slash references |
diagnostics | (internal) | Parse errors |
NodeEvery AST element implements the Node interface. The kind property is a SyntaxKind enum member that identifies the node type. The public API adds helper methods on Node instances returned by the language services layer (NodeObject in src/services/services.ts374-495):
| Method | Description |
|---|---|
getSourceFile() | Enclosing SourceFile |
getStart(sf?, includeJsDoc?) | Start position (skipping trivia) |
getFullStart() | Start position including leading trivia |
getEnd() | End position |
getText(sf?) | Source text substring |
getChildren(sf?) | Child nodes including trivia tokens |
forEachChild(cb, cbArray?) | Iterate direct children |
SyntaxKind EnumSyntaxKind is a large const enum (src/compiler/types.ts40-492) that assigns an integer to every possible node and token kind. Key ranges:
| Range | Description |
|---|---|
Unknown .. EndOfFileToken | Special/trivial tokens |
NumericLiteral .. NoSubstitutionTemplateLiteral | Literal tokens |
OpenBraceToken .. CaretEqualsToken | Punctuation and operators |
BreakKeyword .. DeferKeyword | Keywords |
QualifiedName .. ImportType | Type nodes |
SourceFile | Source file root |
FirstJSDocNode .. LastJSDocNode | JSDoc nodes |
Sources: src/compiler/types.ts40-492 src/services/services.ts374-495
TypeCheckerThe TypeChecker is obtained from program.getTypeChecker(). It provides all semantic analysis queries. It is lazy — most analysis only occurs when a method is called.
Diagram: TypeChecker Key Methods and What They Return
TypeChecker Method GroupsSymbol queries:
| Method | Description |
|---|---|
getSymbolAtLocation(node) | Symbol for an identifier or declaration |
getSymbolsInScope(location, meaning) | All symbols visible at a position |
getExportsOfModule(symbol) | Exported symbols of a module |
getPropertiesOfType(type) | Property symbols of an object type |
getAliasedSymbol(symbol) | Follows import aliases to the original |
getFullyQualifiedName(symbol) | Dotted symbol path |
Type queries:
| Method | Description |
|---|---|
getTypeAtLocation(node) | Inferred/declared type at a node |
getTypeOfSymbolAtLocation(sym, node) | Type of a symbol at a specific usage |
getContextualType(expr) | Expected type from surrounding context |
getBaseTypes(type) | Base types of a class or interface |
getUnionType(types) | Construct a union type |
isAssignableTo(source, target) | Assignability check |
Signature queries:
| Method | Description |
|---|---|
getSignaturesOfType(type, kind) | Call or construct signatures |
getReturnTypeOfSignature(sig) | Return type of a Signature |
getTypePredicateOfSignature(sig) | Type predicate, if any |
getParametersOfSignature(sig) | Parameter symbols |
Display utilities:
| Method | Description |
|---|---|
typeToString(type, enclosingDeclaration?, flags?) | Human-readable type string |
symbolToString(symbol, enclosingDeclaration?, meaning?, flags?) | Human-readable symbol name |
signatureToString(sig, enclosingDeclaration?, flags?, kind?) | Signature display string |
Sources: src/compiler/checker.ts1-1155 tests/baselines/reference/api/typescript.d.ts3000-3200
Symbol and Type InterfacesSymbolinterface Symbol {
flags: SymbolFlags;
escapedName: __String;
declarations?: Declaration[];
valueDeclaration?: Declaration;
members?: SymbolTable;
exports?: SymbolTable;
getName(): string;
getFlags(): SymbolFlags;
getDeclarations(): Declaration[] | undefined;
getDocumentationComment(checker): SymbolDisplayPart[];
getJsDocTags(checker?): JSDocTagInfo[];
}
SymbolFlags is a bitflag enum indicating what kind of thing a symbol represents (e.g., Function, Class, Interface, Variable, TypeAlias, Module, etc.).
Sources: src/services/services.ts656-796 src/compiler/types.ts4000-4100
TypeType is the base interface for all TypeScript types. Concrete kinds are distinguished by TypeFlags:
TypeFlags member | Meaning |
|---|---|
String, Number, Boolean | Primitive types |
StringLiteral, NumberLiteral | Literal types |
Object | Object type (class, interface, type literal) |
Union | Union type (A | B) |
Intersection | Intersection type (A & B) |
TypeParameter | Generic type parameter |
Conditional | Conditional type |
TemplateLiteral | Template literal type |
Any, Unknown, Never, Void | Special types |
Subtypes like UnionType, IntersectionType, ObjectType, and InterfaceType carry additional data. ObjectType uses ObjectFlags to distinguish classes, interfaces, tuples, mapped types, etc.
Sources: src/compiler/types.ts5000-5200 tests/baselines/reference/api/typescript.d.ts1600-1900
NodeBuilderFlags and Type DisplayWhen converting a Type or Symbol back to an AST node (e.g., for generating .d.ts output or display), the TypeChecker accepts NodeBuilderFlags to control the output:
| Flag | Effect |
|---|---|
NoTruncation | Disable type truncation |
WriteArrayAsGenericType | Use Array<T> instead of T[] |
UseStructuralFallback | Fall back to structural type notation |
OmitParameterModifiers | Strip access modifiers from parameters |
UseFullyQualifiedType | Always fully-qualify type names |
Sources: src/compiler/types.ts4800-4900 tests/baselines/reference/api/typescript.d.ts1400-1500
These are exported directly from the ts namespace and commonly used by API consumers:
| Function | Description |
|---|---|
forEachChild(node, cb, cbArray?) | Iterate the immediate children of a node |
getPositionOfLineAndCharacter(sf, line, character) | Line/col to offset |
getLineAndCharacterOfPosition(sf, position) | Offset to line/col |
isIdentifier(node) | Node type guard |
isFunctionDeclaration(node) | Node type guard |
isClassDeclaration(node) | Node type guard |
flattenDiagnosticMessageText(msg, newLine) | Flatten DiagnosticMessageChain to string |
getDefaultLibFilePath(options) | Path to appropriate lib.d.ts |
parseCommandLine(commandLine, readFile?) | Parse CLI-style args |
readConfigFile(fileName, readFile) | Read a tsconfig.json |
parseJsonConfigFileContent(...) | Parse the content of a tsconfig |
findConfigFile(searchPath, fileExists, configName?) | Walk up directories to find tsconfig |
version | The TypeScript compiler version string |
Sources: src/compiler/utilities.ts1-620 src/compiler/program.ts328-340 tests/baselines/reference/api/typescript.d.ts3430-3550
CompilerOptions Key PropertiesCompilerOptions mirrors the properties of tsconfig.json's compilerOptions. Commonly used fields:
| Field | Type | tsconfig equivalent |
|---|---|---|
target | ScriptTarget | "target" |
module | ModuleKind | "module" |
moduleResolution | ModuleResolutionKind | "moduleResolution" |
strict | boolean | "strict" |
outDir | string | "outDir" |
declaration | boolean | "declaration" |
sourceMap | boolean | "sourceMap" |
jsx | JsxEmit | "jsx" |
lib | string[] | "lib" |
noEmit | boolean | "noEmit" |
Sources: src/compiler/commandLineParser.ts1-130 src/compiler/types.ts6000-6200
EmitResult and Diagnosticprogram.emit() returns an EmitResult:
interface EmitResult {
emitSkipped: boolean;
diagnostics: readonly Diagnostic[];
emittedFiles?: string[];
}
Diagnostic is the common error/warning representation:
interface Diagnostic extends DiagnosticRelatedInformation {
category: DiagnosticCategory; // Error, Warning, Message, Suggestion
code: number; // numeric error code
file: SourceFile | undefined;
start: number | undefined;
length: number | undefined;
messageText: string | DiagnosticMessageChain;
}
DiagnosticCategory has values: Warning = 0, Error = 1, Suggestion = 2, Message = 3.
Sources: src/compiler/types.ts1700-1800 tests/baselines/reference/api/typescript.d.ts2000-2100
The public API boundary is enforced by baseline testing. The file tests/baselines/reference/api/typescript.d.ts is generated from the compiled output and checked into the repository. Any PR that changes the public API surface causes this baseline to differ, which fails CI and requires an explicit baseline update. This prevents accidental public API changes.
All internal-only symbols are annotated /** @internal */ in the source. These do not appear in the public baseline and should not be relied upon by external consumers.
Sources: tests/baselines/reference/api/typescript.d.ts1-20 src/compiler/types.ts782-848
BuilderProgram, see Incremental and Project Builds.getDefaultLibFilePath, see Standard Library.Sources: src/services/services.ts1-360 src/server/session.ts1-100 src/compiler/program.ts1-326
Refresh this wiki
This wiki was recently refreshed. Please wait 4 days to refresh again.