0
# Language Services
1
2
Advanced IDE functionality including auto-completion, navigation, refactoring, and code fixes. Provides the foundation for rich development experiences in editors and IDEs.
3
4
## Capabilities
5
6
### Language Service Creation
7
8
Create and configure language service instances.
9
10
```typescript { .api }
11
/**
12
* Create a TypeScript language service
13
* @param host - Language service host providing project information
14
* @param documentRegistry - Document registry for caching (uses default if not provided)
15
* @param syntaxOnlyOrLanguageServiceMode - Syntax-only mode or full language service mode
16
* @returns Language service instance
17
*/
18
function createLanguageService(
19
host: LanguageServiceHost,
20
documentRegistry?: DocumentRegistry,
21
syntaxOnlyOrLanguageServiceMode?: boolean | LanguageServiceMode
22
): LanguageService;
23
24
/**
25
* Create a document registry for caching parsed files
26
* @param useCaseSensitiveFileNames - Whether file names are case sensitive
27
* @param currentDirectory - Current working directory
28
* @returns Document registry instance
29
*/
30
function createDocumentRegistry(
31
useCaseSensitiveFileNames?: boolean,
32
currentDirectory?: string
33
): DocumentRegistry;
34
35
enum LanguageServiceMode {
36
Semantic = 0,
37
PartialSemantic = 1,
38
Syntactic = 2
39
}
40
41
interface LanguageServiceHost extends GetEffectiveTypeRootsHost {
42
getCompilationSettings(): CompilerOptions;
43
getNewLine?(): string;
44
getProjectVersion?(): string;
45
getScriptFileNames(): string[];
46
getScriptKind?(fileName: string): ScriptKind;
47
getScriptVersion(fileName: string): string;
48
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
49
getProjectReferences?(): readonly ProjectReference[] | undefined;
50
getLocalizedDiagnosticMessages?(): any;
51
getCancellationToken?(): HostCancellationToken;
52
getCurrentDirectory(): string;
53
getDefaultLibFileName(options: CompilerOptions): string;
54
log?(s: string): void;
55
trace?(s: string): void;
56
error?(s: string): void;
57
useCaseSensitiveFileNames?(): boolean;
58
readDirectory?(
59
path: string,
60
extensions?: readonly string[],
61
exclude?: readonly string[],
62
include?: readonly string[],
63
depth?: number
64
): string[];
65
readFile?(path: string, encoding?: string): string | undefined;
66
realpath?(path: string): string;
67
fileExists?(path: string): boolean;
68
getTypeRootsVersion?(): number;
69
resolveModuleNames?(
70
moduleNames: string[],
71
containingFile: string,
72
reusedNames: string[] | undefined,
73
redirectedReference: ResolvedProjectReference | undefined,
74
options: CompilerOptions
75
): (ResolvedModule | undefined)[];
76
getResolvedModuleWithFailedLookupLocationsFromCache?(
77
modulename: string,
78
containingFile: string
79
): ResolvedModuleWithFailedLookupLocations | undefined;
80
resolveTypeReferenceDirectives?(
81
typeDirectiveNames: string[],
82
containingFile: string,
83
redirectedReference: ResolvedProjectReference | undefined,
84
options: CompilerOptions
85
): (ResolvedTypeReferenceDirective | undefined)[];
86
hasInvalidatedResolution?(filePath: Path): boolean;
87
hasChangedAutomaticTypeDirectiveNames?(): boolean;
88
getGlobalTypingsCacheLocation?(): string | undefined;
89
}
90
```
91
92
**Usage Examples:**
93
94
```typescript
95
import * as ts from "typescript";
96
97
// Create a simple language service host
98
const files: Record<string, string> = {
99
"example.ts": `
100
interface User {
101
name: string;
102
age: number;
103
}
104
105
function greet(user: User): string {
106
return \`Hello, \${user.name}!\`;
107
}
108
109
const john = { name: "John", age: 30 };
110
greet(jo|n); // cursor at |
111
`
112
};
113
114
const servicesHost: ts.LanguageServiceHost = {
115
getScriptFileNames: () => Object.keys(files),
116
getScriptVersion: () => "1",
117
getScriptSnapshot: (fileName) => {
118
if (!files[fileName]) return undefined;
119
return ts.ScriptSnapshot.fromString(files[fileName]);
120
},
121
getCurrentDirectory: () => "",
122
getCompilationSettings: () => ({
123
module: ts.ModuleKind.CommonJS,
124
target: ts.ScriptTarget.ES2015
125
}),
126
getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
127
fileExists: (fileName) => files[fileName] !== undefined,
128
readFile: (fileName) => files[fileName]
129
};
130
131
const services = ts.createLanguageService(servicesHost);
132
133
// Get completions at cursor position (after "jo")
134
const completions = services.getCompletionsAtPosition("example.ts", 150, {});
135
if (completions) {
136
completions.entries.forEach(entry => {
137
console.log(`${entry.name}: ${entry.kind}`);
138
});
139
}
140
```
141
142
### Auto-Completion
143
144
Get intelligent auto-completion suggestions.
145
146
```typescript { .api }
147
interface LanguageService {
148
/**
149
* Get auto-completion suggestions at a position
150
* @param fileName - Name of source file
151
* @param position - Character position in file
152
* @param options - Completion options
153
* @returns Completion information
154
*/
155
getCompletionsAtPosition(
156
fileName: string,
157
position: number,
158
options?: GetCompletionsAtPositionOptions
159
): CompletionInfo | undefined;
160
161
/**
162
* Get detailed information for a completion entry
163
* @param fileName - Name of source file
164
* @param position - Character position in file
165
* @param name - Name of completion entry
166
* @param formatOptions - Formatting options
167
* @param source - Source of completion entry
168
* @param preferences - User preferences
169
* @returns Detailed completion information
170
*/
171
getCompletionEntryDetails(
172
fileName: string,
173
position: number,
174
name: string,
175
formatOptions?: FormatCodeOptions,
176
source?: string,
177
preferences?: UserPreferences
178
): CompletionEntryDetails | undefined;
179
180
/**
181
* Get symbol for a completion entry
182
* @param fileName - Name of source file
183
* @param position - Character position in file
184
* @param name - Name of completion entry
185
* @param source - Source of completion entry
186
* @returns Symbol information
187
*/
188
getCompletionEntrySymbol(
189
fileName: string,
190
position: number,
191
name: string,
192
source?: string
193
): Symbol | undefined;
194
}
195
196
interface CompletionInfo {
197
entries: readonly CompletionEntry[];
198
isGlobalCompletion: boolean;
199
isMemberCompletion: boolean;
200
isNewIdentifierLocation: boolean;
201
optionalReplacementSpan?: TextSpan;
202
}
203
204
interface CompletionEntry {
205
name: string;
206
kind: ScriptElementKind;
207
kindModifiers?: string;
208
sortText: string;
209
insertText?: string;
210
replacementSpan?: TextSpan;
211
hasAction?: true;
212
source?: string;
213
isRecommended?: true;
214
isFromUncheckedFile?: true;
215
isPackageJsonImport?: true;
216
}
217
```
218
219
### Navigation and Definition
220
221
Navigate to definitions, implementations, and references.
222
223
```typescript { .api }
224
interface LanguageService {
225
/**
226
* Get definition locations for a symbol
227
* @param fileName - Name of source file
228
* @param position - Character position in file
229
* @returns Array of definition locations
230
*/
231
getDefinitionAtPosition(
232
fileName: string,
233
position: number
234
): readonly DefinitionInfo[] | undefined;
235
236
/**
237
* Get definition with bound span
238
* @param fileName - Name of source file
239
* @param position - Character position in file
240
* @returns Definition info with bound span
241
*/
242
getDefinitionAndBoundSpan(
243
fileName: string,
244
position: number
245
): DefinitionInfoAndBoundSpan | undefined;
246
247
/**
248
* Get type definition locations
249
* @param fileName - Name of source file
250
* @param position - Character position in file
251
* @returns Array of type definition locations
252
*/
253
getTypeDefinitionAtPosition(
254
fileName: string,
255
position: number
256
): readonly DefinitionInfo[] | undefined;
257
258
/**
259
* Get implementation locations
260
* @param fileName - Name of source file
261
* @param position - Character position in file
262
* @returns Array of implementation locations
263
*/
264
getImplementationAtPosition(
265
fileName: string,
266
position: number
267
): readonly ImplementationLocation[] | undefined;
268
269
/**
270
* Find all references to a symbol
271
* @param fileName - Name of source file
272
* @param position - Character position in file
273
* @returns Array of referenced symbols with locations
274
*/
275
findReferences(
276
fileName: string,
277
position: number
278
): ReferencedSymbol[] | undefined;
279
280
/**
281
* Find rename locations for a symbol
282
* @param fileName - Name of source file
283
* @param position - Character position in file
284
* @param findInStrings - Whether to find in string literals
285
* @param findInComments - Whether to find in comments
286
* @param providePrefixAndSuffixTextForRename - Whether to provide prefix/suffix text
287
* @returns Array of rename locations
288
*/
289
findRenameLocations(
290
fileName: string,
291
position: number,
292
findInStrings: boolean,
293
findInComments: boolean,
294
providePrefixAndSuffixTextForRename?: boolean
295
): readonly RenameLocation[] | undefined;
296
}
297
298
interface DefinitionInfo extends DocumentSpan {
299
kind: ScriptElementKind;
300
name: string;
301
containerKind: ScriptElementKind;
302
containerName: string;
303
unverified?: boolean;
304
}
305
306
interface DocumentSpan {
307
textSpan: TextSpan;
308
fileName: string;
309
originalTextSpan?: TextSpan;
310
originalFileName?: string;
311
contextSpan?: TextSpan;
312
}
313
314
interface ReferenceEntry extends DocumentSpan {
315
isWriteAccess: boolean;
316
isInString?: true;
317
}
318
319
interface ReferencedSymbol {
320
definition?: ReferencedSymbolDefinitionInfo;
321
references: ReferenceEntry[];
322
}
323
```
324
325
### Refactoring and Code Fixes
326
327
Get available refactorings and apply code fixes.
328
329
```typescript { .api }
330
interface LanguageService {
331
/**
332
* Get applicable refactors at a position or range
333
* @param fileName - Name of source file
334
* @param positionOrRange - Position or text range
335
* @param preferences - User preferences
336
* @returns Array of applicable refactors
337
*/
338
getApplicableRefactors(
339
fileName: string,
340
positionOrRange: number | TextRange,
341
preferences?: UserPreferences
342
): ApplicableRefactorInfo[];
343
344
/**
345
* Get edits for a specific refactor
346
* @param fileName - Name of source file
347
* @param formatOptions - Code formatting options
348
* @param positionOrRange - Position or text range
349
* @param refactorName - Name of refactor to apply
350
* @param actionName - Name of specific action
351
* @param preferences - User preferences
352
* @returns File text changes for refactor
353
*/
354
getEditsForRefactor(
355
fileName: string,
356
formatOptions: FormatCodeOptions,
357
positionOrRange: number | TextRange,
358
refactorName: string,
359
actionName: string,
360
preferences?: UserPreferences
361
): RefactorEditInfo | undefined;
362
363
/**
364
* Organize import statements
365
* @param scope - Scope of organization (file or project)
366
* @param formatOptions - Code formatting options
367
* @param preferences - User preferences
368
* @returns Array of file changes
369
*/
370
organizeImports(
371
scope: OrganizeImportsScope,
372
formatOptions: FormatCodeOptions,
373
preferences?: UserPreferences
374
): readonly FileTextChanges[];
375
376
/**
377
* Get edits for renaming a file
378
* @param oldFilePath - Current file path
379
* @param newFilePath - New file path
380
* @param formatOptions - Code formatting options
381
* @param preferences - User preferences
382
* @returns Array of file changes
383
*/
384
getEditsForFileRename(
385
oldFilePath: string,
386
newFilePath: string,
387
formatOptions: FormatCodeOptions,
388
preferences?: UserPreferences
389
): readonly FileTextChanges[];
390
391
/**
392
* Get code fixes for errors at a position
393
* @param fileName - Name of source file
394
* @param start - Start position of error
395
* @param end - End position of error
396
* @param errorCodes - Error codes to fix
397
* @param formatOptions - Code formatting options
398
* @param preferences - User preferences
399
* @returns Array of code fix actions
400
*/
401
getCodeFixesAtPosition(
402
fileName: string,
403
start: number,
404
end: number,
405
errorCodes: readonly number[],
406
formatOptions: FormatCodeOptions,
407
preferences: UserPreferences
408
): readonly CodeFixAction[];
409
}
410
411
interface ApplicableRefactorInfo {
412
name: string;
413
description: string;
414
actions: RefactorActionInfo[];
415
inlineable?: boolean;
416
}
417
418
interface RefactorActionInfo {
419
name: string;
420
description: string;
421
notApplicableReason?: string;
422
}
423
424
interface FileTextChanges {
425
fileName: string;
426
textChanges: readonly TextChange[];
427
isNewFile?: boolean;
428
}
429
430
interface TextChange {
431
span: TextSpan;
432
newText: string;
433
}
434
```
435
436
### Information and Diagnostics
437
438
Get hover information, signature help, and diagnostics.
439
440
```typescript { .api }
441
interface LanguageService {
442
/**
443
* Get quick info (hover) at a position
444
* @param fileName - Name of source file
445
* @param position - Character position in file
446
* @returns Quick info display parts
447
*/
448
getQuickInfoAtPosition(
449
fileName: string,
450
position: number
451
): QuickInfo | undefined;
452
453
/**
454
* Get signature help for function calls
455
* @param fileName - Name of source file
456
* @param position - Character position in file
457
* @param options - Signature help options
458
* @returns Signature help information
459
*/
460
getSignatureHelpItems(
461
fileName: string,
462
position: number,
463
options?: SignatureHelpItemsOptions
464
): SignatureHelpItems | undefined;
465
466
/**
467
* Get navigation bar items for file outline
468
* @param fileName - Name of source file
469
* @returns Array of navigation bar items
470
*/
471
getNavigationBarItems(fileName: string): NavigationBarItem[];
472
473
/**
474
* Get hierarchical navigation tree
475
* @param fileName - Name of source file
476
* @returns Navigation tree root
477
*/
478
getNavigationTree(fileName: string): NavigationTree;
479
480
/**
481
* Get collapsible regions (outlining spans)
482
* @param fileName - Name of source file
483
* @returns Array of outlining spans
484
*/
485
getOutliningSpans(fileName: string): OutliningSpan[];
486
487
/**
488
* Get document highlights for a symbol
489
* @param fileName - Name of source file
490
* @param position - Character position in file
491
* @param filesToSearch - Files to search for highlights
492
* @returns Array of document highlights
493
*/
494
getDocumentHighlights(
495
fileName: string,
496
position: number,
497
filesToSearch: string[]
498
): DocumentHighlights[] | undefined;
499
500
/**
501
* Get syntactic diagnostics for a file
502
* @param fileName - Name of source file
503
* @returns Array of syntactic diagnostics
504
*/
505
getSyntacticDiagnostics(fileName: string): readonly Diagnostic[];
506
507
/**
508
* Get semantic diagnostics for a file
509
* @param fileName - Name of source file
510
* @returns Array of semantic diagnostics
511
*/
512
getSemanticDiagnostics(fileName: string): readonly Diagnostic[];
513
514
/**
515
* Get suggestion diagnostics for a file
516
* @param fileName - Name of source file
517
* @returns Array of suggestion diagnostics
518
*/
519
getSuggestionDiagnostics(fileName: string): readonly DiagnosticWithLocation[];
520
}
521
522
interface QuickInfo {
523
kind: ScriptElementKind;
524
kindModifiers: string;
525
textSpan: TextSpan;
526
displayParts?: SymbolDisplayPart[];
527
documentation?: SymbolDisplayPart[];
528
tags?: JSDocTagInfo[];
529
}
530
531
interface SignatureHelpItems {
532
items: SignatureHelpItem[];
533
applicableSpan: TextSpan;
534
selectedItemIndex: number;
535
argumentIndex: number;
536
argumentCount: number;
537
}
538
539
interface NavigationBarItem {
540
text: string;
541
kind: ScriptElementKind;
542
kindModifiers: string;
543
spans: TextSpan[];
544
childItems?: NavigationBarItem[];
545
indent: number;
546
bolded: boolean;
547
grayed: boolean;
548
}
549
```
550
551
### Code Formatting
552
553
Format TypeScript code according to style rules.
554
555
```typescript { .api }
556
interface LanguageService {
557
/**
558
* Get formatting edits for a text range
559
* @param fileName - Name of source file
560
* @param start - Start position of range
561
* @param end - End position of range
562
* @param options - Formatting options
563
* @returns Array of text changes
564
*/
565
getFormattingEditsForRange(
566
fileName: string,
567
start: number,
568
end: number,
569
options: FormatCodeOptions
570
): readonly TextChange[];
571
572
/**
573
* Get formatting edits for entire document
574
* @param fileName - Name of source file
575
* @param options - Formatting options
576
* @returns Array of text changes
577
*/
578
getFormattingEditsForDocument(
579
fileName: string,
580
options: FormatCodeOptions
581
): readonly TextChange[];
582
583
/**
584
* Get formatting edits after a keystroke
585
* @param fileName - Name of source file
586
* @param position - Position of keystroke
587
* @param key - Character that was typed
588
* @param options - Formatting options
589
* @returns Array of text changes
590
*/
591
getFormattingEditsAfterKeystroke(
592
fileName: string,
593
position: number,
594
key: string,
595
options: FormatCodeOptions
596
): readonly TextChange[];
597
}
598
599
interface FormatCodeOptions extends EditorOptions {
600
insertSpaceAfterCommaDelimiter?: boolean;
601
insertSpaceAfterSemicolonInForStatements?: boolean;
602
insertSpaceBeforeAndAfterBinaryOperators?: boolean;
603
insertSpaceAfterConstructor?: boolean;
604
insertSpaceAfterKeywordsInControlFlowStatements?: boolean;
605
insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean;
606
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean;
607
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean;
608
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean;
609
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean;
610
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean;
611
insertSpaceAfterTypeAssertion?: boolean;
612
insertSpaceBeforeFunctionParenthesis?: boolean;
613
placeOpenBraceOnNewLineForFunctions?: boolean;
614
placeOpenBraceOnNewLineForControlBlocks?: boolean;
615
insertSpaceBeforeTypeAnnotation?: boolean;
616
semicolons?: SemicolonPreference;
617
}
618
```
619
620
## Types
621
622
### Core Service Types
623
624
```typescript { .api }
625
enum ScriptElementKind {
626
unknown = "",
627
warning = "warning",
628
keyword = "keyword",
629
scriptElement = "script",
630
moduleElement = "module",
631
classElement = "class",
632
localClassElement = "local class",
633
interfaceElement = "interface",
634
typeElement = "type",
635
enumElement = "enum",
636
enumMemberElement = "enum member",
637
variableElement = "var",
638
localVariableElement = "local var",
639
functionElement = "function",
640
localFunctionElement = "local function",
641
memberFunctionElement = "method",
642
memberGetAccessorElement = "getter",
643
memberSetAccessorElement = "setter",
644
memberVariableElement = "property",
645
constructorImplementationElement = "constructor",
646
callSignatureElement = "call",
647
indexSignatureElement = "index",
648
constructSignatureElement = "construct",
649
parameterElement = "parameter",
650
typeParameterElement = "type parameter",
651
primitiveType = "primitive type",
652
label = "label",
653
alias = "alias",
654
constElement = "const",
655
letElement = "let",
656
directory = "directory",
657
externalModuleName = "external module name",
658
jsxAttribute = "JSX attribute",
659
string = "string"
660
}
661
662
interface TextSpan {
663
start: number;
664
length: number;
665
}
666
667
interface SymbolDisplayPart {
668
text: string;
669
kind: string;
670
}
671
672
interface JSDocTagInfo {
673
name: string;
674
text?: SymbolDisplayPart[];
675
}
676
```
677
678
### User Preferences
679
680
```typescript { .api }
681
interface UserPreferences {
682
readonly disableSuggestions?: boolean;
683
readonly quotePreference?: "auto" | "double" | "single";
684
readonly includeCompletionsForModuleExports?: boolean;
685
readonly includeCompletionsForImportStatements?: boolean;
686
readonly includeCompletionsWithSnippetText?: boolean;
687
readonly includeAutomaticOptionalChainCompletions?: boolean;
688
readonly includeCompletionsWithInsertText?: boolean;
689
readonly allowTextChangesInNewFiles?: boolean;
690
readonly providePrefixAndSuffixTextForRename?: boolean;
691
readonly includePackageJsonAutoImports?: "auto" | "on" | "off";
692
readonly provideRefactorNotApplicableReason?: boolean;
693
readonly allowRenameOfImportPath?: boolean;
694
readonly includeCompletionsWithClassMemberSnippets?: boolean;
695
readonly includeCompletionsWithObjectLiteralMethodSnippets?: boolean;
696
readonly useLabelDetailsInCompletionEntries?: boolean;
697
readonly allowIncompleteCompletions?: boolean;
698
readonly displayPartsForJSDoc?: boolean;
699
readonly generateReturnInDocTemplate?: boolean;
700
}
701
```