This page documents the code completions service in TypeScript's language service. It covers how completion candidates are generated at a given cursor position, how the type checker is used to enumerate symbols in scope, how auto-import completions are handled, and how string and path completions work.
For the broader LanguageService API that hosts this feature, see Language Service. For signature help when typing function arguments, see Signature Help. For JSDoc tag name completions, see JSDoc Support.
The completions service is exposed via three methods on the LanguageService interface (src/services/types.ts):
| Method | Returns | Purpose |
|---|---|---|
getCompletionsAtPosition(fileName, position, options) | CompletionInfo | undefined | Full list of completion candidates at a position |
getCompletionEntryDetails(fileName, position, name, ...) | CompletionEntryDetails | undefined | Detailed info (docs, type, code actions) for a selected entry |
getCompletionEntrySymbol(fileName, position, name, ...) | Symbol | undefined | The compiler Symbol backing a completion entry |
| Type | Role |
|---|---|
CompletionInfo | Top-level response containing entries and metadata flags |
CompletionEntry | A single completion candidate |
CompletionEntryDetails | Full documentation, type display, and code actions for one entry |
CompletionEntryData | Opaque token attached to an entry; used when resolving details |
CompletionEntryDataUnresolved | Auto-import with no module specifier yet computed |
CompletionEntryDataResolved | Auto-import with a fully resolved module specifier |
GetCompletionsAtPositionOptions | Options passed alongside the request |
CompletionsTriggerCharacter | Trigger characters: . " ' ` / @ < # |
CompletionTriggerKind | How completions were invoked (Invoked, TriggerCharacter, TriggerForIncompleteCompletions) |
CompletionInfoFlags | Bitfield: MayIncludeAutoImports, IsImportStatementCompletion, IsContinuation, etc. |
UserPreferences | Per-user toggles for completion behavior |
CompletionInfo ShapeCompletionInfo {
isGlobalCompletion: boolean // true if position is at global scope
isMemberCompletion: boolean // true after . or ?.
isNewIdentifierLocation: boolean // true where a new name can be declared
optionalReplacementSpan?: TextSpan
entries: CompletionEntry[]
flags?: CompletionInfoFlags
isIncomplete?: boolean // true when auto-import entries are still loading
}
CompletionEntry ShapeCompletionEntry {
name: string
kind: ScriptElementKind // function | variable | class | keyword | ...
sortText: string // editor ordering key
insertText?: string // differs from name for snippets or import completions
replacementSpan?: TextSpan // range in source to overwrite
hasAction?: true // detail resolution will produce a CodeAction
source?: string // module specifier (auto-imports)
data?: CompletionEntryData // used to resolve detail on demand
isSnippet?: true
labelDetails?: CompletionEntryLabelDetails
}
Sources: src/services/types.ts1-300 tests/baselines/reference/api/typescript.d.ts1-130 src/services/completions.ts1-120
High-level flow from API call to CompletionInfo:
Sources: src/services/completions.ts1-500 src/services/services.ts1-200
Before any candidates are generated, getCompletionData determines the semantic context of the cursor. It locates the enclosing token and walks the AST.
Context determination flow:
Key utility functions:
| Function | File | Purpose |
|---|---|---|
getTouchingPropertyName | src/services/utilities.ts | Token touching position, for identifiers |
getTokenAtPosition | src/services/utilities.ts | Exact token at position |
findPrecedingToken | src/services/utilities.ts | Token immediately before position |
getContextualTypeFromParent | src/compiler/checker.ts | Contextual type at position |
getReplacementSpanForContextToken | src/services/completions.ts | Span to replace when inserting |
getSwitchedType | src/services/completions.ts | Type of switch expression, for case completions |
Sources: src/services/completions.ts100-400 src/services/utilities.ts1-200
For most contexts, completions are derived from the type checker's symbol tables.
Symbol collection flow:
The internal SortText namespace in src/services/completions.ts defines string constants that control list ordering in the editor:
| SortText bucket | Description |
|---|---|
LocalDeclarationPriority | Parameters and local variables |
LocationPriority | Symbols declared near the cursor |
OptionalMember | Optional properties (lower priority) |
MemberDeclaredBySpreadAssignment | Spread-contributed members |
SuggestedClassMembers | Abstract method override candidates |
GlobalsOrKeywords | Global symbols and language keywords |
AutoImportSuggestions | Auto-import candidates (lowest priority) |
JavascriptIdentifiers | JS-only identifier suggestions |
Sources: src/services/completions.ts200-700
Auto-import completions suggest symbols from modules that are not yet imported in the current file. This is the largest and most complex part of the completions service.
Auto-import architecture:
CompletionEntryData variants:
| Variant | When used |
|---|---|
CompletionEntryDataUnresolved | Module specifier not yet computed (lazy/incomplete) |
CompletionEntryDataResolved | Module specifier already resolved |
When CompletionInfo.isIncomplete is true, the editor may call getCompletionsAtPosition again with CompletionTriggerKind.TriggerForIncompleteCompletions. The IncompleteCompletionsCache in src/server/editorServices.ts stores the partial result to avoid full recomputation.
Sources: src/services/completions.ts400-900 src/services/codefixes/importFixes.ts1-100 src/server/editorServices.ts1-200
The StringCompletions module (imported into src/services/completions.ts from ts.Completions) handles completions inside string literals.
Contexts handled:
| Context | Examples |
|---|---|
Module specifier in import | import ... from "./ |
require() call argument | require("./ |
/// <reference path="..."> | Triple-slash path |
| Import attribute values | with { type: " |
| String union type literal | When contextual type is a union of string literals |
Path completions use the CompilerHost's file system access to enumerate directories and files. Results are filtered to files matching supported TypeScript extensions.
Sources: src/services/completions.ts1-50 src/services/completions.ts900-1200
In JSX contexts the service generates additional completion categories:
JSX.IntrinsicElements (intrinsic) and imported components (value-based)props type of the element's component typeThe JSX context is identified by detecting that the token is inside a JsxOpeningElement, JsxSelfClosingElement, or JsxAttribute node.
Sources: src/services/completions.ts500-900
Keywords (if, function, return, async, await, yield, etc.) are included in the entry list when the cursor is at a statement or expression position. Contextual filtering applies:
await — only inside async functions or top-level modules with --module es2022+yield — only inside generator functionstype/interface — only at declaration positionsKeywords receive ScriptElementKind.keyword and a SortText.GlobalsOrKeywords value, placing them after symbol-based completions.
Sources: src/services/completions.ts600-900
When the user selects an entry, the editor calls getCompletionEntryDetails:
For auto-import entries with CompletionEntryDataUnresolved, the detail step resolves the module specifier by calling into moduleSpecifiers.ts and then produces the CodeAction via importFixes.ts.
Sources: src/services/completions.ts900-1200 src/services/codefixes/importFixes.ts1-100
The UserPreferences interface (src/services/types.ts) controls completion behavior:
| Preference | Effect |
|---|---|
includeCompletionsForModuleExports | Enables auto-import candidates |
includeAutomaticOptionalChainCompletions | Suggests ?. for possibly-undefined access |
includeCompletionsWithInsertText | Includes entries where insertText ≠ name |
includeCompletionsWithSnippetText | Allows tab-stop snippets in insertText |
useLabelDetailsInCompletionEntries | Populates CompletionEntryLabelDetails |
allowIncompleteCompletions | Permits isIncomplete results (lazy auto-imports) |
importModuleSpecifierPreference | shortest / relative / non-relative for auto-import paths |
importModuleSpecifierEnding | Controls .js / .ts extension in specifiers |
Sources: src/services/types.ts1-300
Mapping high-level concepts to concrete code entities:
Sources: src/services/completions.ts1-1200 src/services/services.ts1-200 src/compiler/checker.ts1-100 src/server/session.ts1-200 src/server/editorServices.ts1-200 src/services/codefixes/importFixes.ts1-100
When accessed via tsserver (see tsserver Protocol):
CompletionInfo or completionInfo requestSession.getCompletions in src/server/session.ts dispatches to the project's LanguageServicegetCompletionsAtPosition runs on the project's ProgramCompletionInfo is serialized to the JSON protocol format and returnedThe IncompleteCompletionsCache stored on ProjectService in src/server/editorServices.ts holds the last partial CompletionInfo when isIncomplete is true, enabling follow-up TriggerForIncompleteCompletions requests to extend the list without full recomputation.
Sources: src/server/session.ts1-200 src/server/editorServices.ts1-200 src/server/project.ts1-100
Refresh this wiki
This wiki was recently refreshed. Please wait 4 days to refresh again.