TypeScript is a programming language and compiler system that extends JavaScript with optional static types for building large-scale applications.
npx @tessl/cli install tessl/npm-typescript@5.9.00
# TypeScript
1
2
TypeScript is a comprehensive programming language and compiler system that extends JavaScript by adding optional static type annotations. It enables developers to build large-scale applications with enhanced tooling support, early error detection, and improved code maintainability. The TypeScript compiler (tsc) transforms TypeScript code into readable, standards-based JavaScript, while the TypeScript Language Server (tsserver) provides rich development experiences with intelligent code completion, refactoring, and error checking.
3
4
## Package Information
5
6
- **Package Name**: typescript
7
- **Package Type**: npm
8
- **Language**: TypeScript (self-hosting)
9
- **Installation**: `npm install -D typescript`
10
11
## Core Imports
12
13
```typescript
14
import * as ts from "typescript";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const ts = require("typescript");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import * as ts from "typescript";
27
28
// Parse TypeScript source code
29
const sourceFile = ts.createSourceFile(
30
"example.ts",
31
'const greeting: string = "Hello, World!";',
32
ts.ScriptTarget.Latest
33
);
34
35
// Create a program with the source file
36
const program = ts.createProgram(["example.ts"], {
37
target: ts.ScriptTarget.ES2015,
38
module: ts.ModuleKind.CommonJS
39
}, {
40
getSourceFile: (fileName) => fileName === "example.ts" ? sourceFile : undefined,
41
writeFile: () => {},
42
getCurrentDirectory: () => "",
43
getDirectories: () => [],
44
fileExists: () => true,
45
readFile: () => "",
46
getCanonicalFileName: (fileName) => fileName,
47
useCaseSensitiveFileNames: () => true,
48
getNewLine: () => "\n"
49
});
50
51
// Get type checker for semantic analysis
52
const typeChecker = program.getTypeChecker();
53
54
// Emit JavaScript output
55
const result = program.emit();
56
console.log(`Emit result: ${result.emitSkipped ? 'failed' : 'success'}`);
57
```
58
59
## Architecture
60
61
TypeScript's API is organized into several key components:
62
63
- **Compiler Core**: Parsing, type checking, and code generation (`createSourceFile`, `createProgram`, `TypeChecker`)
64
- **Language Services**: IDE functionality like completion, navigation, and refactoring (`LanguageService`)
65
- **Server Protocol**: TSServer for editor integration (`ts.server` namespace)
66
- **Transpilation**: Simple TypeScript-to-JavaScript conversion (`transpileModule`)
67
- **Node Factory**: AST node creation and manipulation for transformations
68
- **Utilities**: Helper functions for AST traversal, type guards, and text operations
69
70
## Capabilities
71
72
### Parser and AST
73
74
Core parsing functionality that converts TypeScript source code into Abstract Syntax Trees (AST). Essential for any tool that needs to analyze or manipulate TypeScript code.
75
76
```typescript { .api }
77
function createSourceFile(
78
fileName: string,
79
sourceText: string,
80
languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions,
81
setParentNodes?: boolean,
82
scriptKind?: ScriptKind
83
): SourceFile;
84
85
function forEachChild<T>(
86
node: Node,
87
cbNode: (node: Node) => T | undefined,
88
cbNodes?: (nodes: NodeArray<Node>) => T | undefined
89
): T | undefined;
90
```
91
92
[Parser and AST](./parser-ast.md)
93
94
### Type Checker
95
96
Comprehensive type analysis system that provides semantic information about TypeScript code. Powers features like type inference, error detection, and symbol resolution.
97
98
```typescript { .api }
99
function createTypeChecker(host: TypeCheckerHost): TypeChecker;
100
101
interface TypeChecker {
102
getTypeAtLocation(node: Node): Type;
103
getSymbolAtLocation(node: Node): Symbol | undefined;
104
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined;
105
typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined;
106
}
107
```
108
109
[Type Checker](./type-checker.md)
110
111
### Program and Compilation
112
113
High-level compilation interface that manages multiple source files, handles module resolution, and orchestrates the compilation process from parsing to emit.
114
115
```typescript { .api }
116
function createProgram(
117
rootNames: readonly string[],
118
options: CompilerOptions,
119
host?: CompilerHost,
120
oldProgram?: Program,
121
configFileParsingDiagnostics?: readonly Diagnostic[]
122
): Program;
123
124
interface Program {
125
getRootFileNames(): readonly string[];
126
getSourceFiles(): readonly SourceFile[];
127
getTypeChecker(): TypeChecker;
128
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult;
129
}
130
```
131
132
[Program and Compilation](./program-compilation.md)
133
134
### Language Services
135
136
Advanced IDE functionality including auto-completion, navigation, refactoring, and code fixes. Provides the foundation for rich development experiences in editors and IDEs.
137
138
```typescript { .api }
139
function createLanguageService(
140
host: LanguageServiceHost,
141
documentRegistry?: DocumentRegistry,
142
syntaxOnlyOrLanguageServiceMode?: boolean | LanguageServiceMode
143
): LanguageService;
144
145
interface LanguageService {
146
getCompletionsAtPosition(fileName: string, position: number, options?: GetCompletionsAtPositionOptions): CompletionInfo | undefined;
147
getDefinitionAtPosition(fileName: string, position: number): readonly DefinitionInfo[] | undefined;
148
findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined;
149
getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences?: UserPreferences): ApplicableRefactorInfo[];
150
}
151
```
152
153
[Language Services](./language-services.md)
154
155
### Transpilation
156
157
Simple and fast TypeScript-to-JavaScript conversion without full type checking. Ideal for build tools and development servers that need quick compilation.
158
159
```typescript { .api }
160
function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput;
161
162
function transpile(
163
input: string,
164
compilerOptions?: CompilerOptions,
165
fileName?: string,
166
diagnostics?: Diagnostic[],
167
moduleName?: string
168
): string;
169
170
interface TranspileOptions {
171
compilerOptions?: CompilerOptions;
172
fileName?: string;
173
reportDiagnostics?: boolean;
174
moduleName?: string;
175
renamedDependencies?: MapLike<string>;
176
}
177
```
178
179
[Transpilation](./transpilation.md)
180
181
### Node Factory and Transformers
182
183
AST node creation and transformation system for building custom TypeScript transformers and code generation tools.
184
185
```typescript { .api }
186
function createNodeFactory(flags: NodeFactoryFlags, baseFactory?: BaseNodeFactory): NodeFactory;
187
188
function transformNodes<T extends Node>(
189
resolver: EmitResolver | undefined,
190
host: EmitHost | undefined,
191
options: CompilerOptions,
192
nodes: readonly T[],
193
transformers: readonly TransformerFactory<T>[],
194
allowDtsFiles: boolean
195
): TransformationResult<T>;
196
197
interface NodeFactory {
198
createIdentifier(text: string): Identifier;
199
createStringLiteral(text: string, isSingleQuote?: boolean): StringLiteral;
200
createFunctionDeclaration(
201
modifiers: readonly Modifier[] | undefined,
202
asteriskToken: AsteriskToken | undefined,
203
name: string | Identifier | undefined,
204
typeParameters: readonly TypeParameterDeclaration[] | undefined,
205
parameters: readonly ParameterDeclaration[],
206
type: TypeNode | undefined,
207
body: Block | undefined
208
): FunctionDeclaration;
209
}
210
```
211
212
[Node Factory and Transformers](./node-factory-transformers.md)
213
214
### Utilities and Helpers
215
216
Essential utility functions for working with TypeScript AST nodes, including type guards, text operations, and traversal helpers.
217
218
```typescript { .api }
219
function isIdentifier(node: Node): node is Identifier;
220
function isStringLiteral(node: Node): node is StringLiteral;
221
function isFunctionDeclaration(node: Node): node is FunctionDeclaration;
222
223
function getOriginalNode(node: Node, nodeTest?: (node: Node) => node is Node): Node;
224
function findAncestor<T extends Node>(node: Node, callback: (element: Node) => element is T): T | undefined;
225
226
function escapeLeadingUnderscores(identifier: string): __String;
227
function unescapeLeadingUnderscores(identifier: __String): string;
228
```
229
230
[Utilities and Helpers](./utilities-helpers.md)
231
232
### Command Line and Configuration
233
234
Configuration management and command-line argument parsing for building TypeScript tooling and custom compilers.
235
236
```typescript { .api }
237
function parseCommandLine(commandLine: readonly string[], readFile?: (path: string) => string | undefined): ParsedCommandLine;
238
239
function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic };
240
241
function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic };
242
243
interface CompilerOptions {
244
target?: ScriptTarget;
245
module?: ModuleKind;
246
strict?: boolean;
247
esModuleInterop?: boolean;
248
skipLibCheck?: boolean;
249
declaration?: boolean;
250
outDir?: string;
251
rootDir?: string;
252
// ... 200+ more options
253
}
254
```
255
256
[Command Line and Configuration](./command-line-config.md)
257
258
## Types
259
260
### Core AST Types
261
262
```typescript { .api }
263
interface Node {
264
kind: SyntaxKind;
265
flags: NodeFlags;
266
pos: number;
267
end: number;
268
parent: Node;
269
}
270
271
interface SourceFile extends Declaration {
272
kind: SyntaxKind.SourceFile;
273
statements: NodeArray<Statement>;
274
endOfFileToken: Token<SyntaxKind.EndOfFileToken>;
275
fileName: string;
276
text: string;
277
languageVersion: ScriptTarget;
278
}
279
280
interface Identifier extends Declaration {
281
kind: SyntaxKind.Identifier;
282
text: string;
283
originalKeywordKind: SyntaxKind;
284
}
285
286
enum SyntaxKind {
287
Unknown = 0,
288
EndOfFileToken = 1,
289
SingleLineCommentTrivia = 2,
290
MultiLineCommentTrivia = 3,
291
// ... 400+ syntax kinds
292
Identifier = 79,
293
StringLiteral = 10,
294
FunctionDeclaration = 256,
295
ClassDeclaration = 257,
296
// ... many more
297
}
298
```
299
300
### Diagnostic Types
301
302
```typescript { .api }
303
interface Diagnostic {
304
file: SourceFile | undefined;
305
start: number | undefined;
306
length: number | undefined;
307
messageText: string | DiagnosticMessageChain;
308
category: DiagnosticCategory;
309
code: number;
310
source?: string;
311
}
312
313
enum DiagnosticCategory {
314
Warning = 0,
315
Error = 1,
316
Suggestion = 2,
317
Message = 3
318
}
319
320
interface DiagnosticMessageChain {
321
messageText: string;
322
category: DiagnosticCategory;
323
code: number;
324
next?: DiagnosticMessageChain[];
325
}
326
```