TS 中文文档 TS 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • 入门教程

    • TypeScript 手册
    • 基础知识
    • 日常类型
    • 类型缩小
    • 更多关于函数
    • 对象类型
    • 从类型创建类型
    • 泛型
    • Keyof 类型运算符
    • Typeof 类型运算符
    • 索引访问类型
    • 条件类型
    • 映射类型
    • 模板字面类型
    • 类
    • 模块
  • 参考手册

  • 项目配置

TypeScript Language Server


Language Server Protocol implementation for TypeScript wrapping tsserver.

Based on concepts and ideas from https://github.com/prabirshrestha/typescript-language-server and originally maintained by TypeFox

Maintained by a community of contributors like you

Installing
Running the language server
CLI Options
initializationOptions
workspace/didChangeConfiguration
Code actions on save
Workspace commands (workspace/executeCommand)
Go to Source Definition
Apply Workspace Edits
Apply Code Action
Apply Refactoring
Organize Imports
Rename File
Configure plugin

Inlay hints (textDocument/inlayHint)
TypeScript Version Notification
Supported Protocol features
Development
Build
Test
Watch
Publishing

Installing


  1. ``` shell
  2. npm install -g typescript-language-server typescript
  3. ```

Running the language server


  1. ``` sh
  2. typescript-language-server --stdio

  3. ```

CLI Options


  1. ``` sh
  2.   Usage: typescript-language-server [options]

  3.   Options:

  4.     -V, --version                          output the version number
  5.     --stdio                                use stdio (required option)
  6.     --log-level <log-level>                A number indicating the log level (4 = log, 3 = info, 2 = warn, 1 = error). Defaults to `3`.
  7.     --tsserver-log-verbosity <verbosity>   [deprecated] Specify tsserver log verbosity (off, terse, normal, verbose). Defaults to `normal`. example: --tsserver-log-verbosity=verbose
  8.     --tsserver-path <path>                 [deprecated] Specify path to tsserver directory. example: --tsserver-path=/Users/me/typescript/lib/
  9.     -h, --help                             output usage information

  10. ```

The --tsserver-log-verbosity and --tsserver-path options are deprecated and it is recommended to pass those through corresponding tsserver.* initializationOptions instead.


Note: The path passed to --tsserver-path should be a path to the [...]/typescript/lib/tssserver.js file or to the [...]/typescript/lib/ directory and not to the shell script [...]/node_modules/.bin/tsserver. Though for backward-compatibility reasons, the server will try to do the right thing even when passed a path to the shell script.


initializationOptions


The language server accepts various settings through the initializationOptions object passed through the initialize request. Refer to your LSP client's documentation on how to set these. Here is the list of supported options:

Setting Type Description
:--- :--- :---
hostInfo string Information about the host, for example "Emacs 24.4" or "Sublime Text v3075". Default: undefined
completionDisableFilterText boolean Don't set filterText property on completion items. Default: false
disableAutomaticTypingAcquisition boolean Disables tsserver from automatically fetching missing type definitions (@types packages) for external modules.
maxTsServerMemory number The maximum size of the V8's old memory section in megabytes (for example 4096 means 4GB). The default value is dynamically configured by Node so can differ per system. Increase for very big projects that exceed allowed memory usage. Default: undefined
npmLocation string Specifies the path to the NPM executable used for Automatic Type Acquisition.
locale string The locale to use to show error messages.
plugins object[] An array of { name: string, location: string } objects for registering a Typescript plugins. Default: []
preferences object Preferences passed to the Typescript (tsserver) process. See below for more
tsserver object Options related to the tsserver process. See below for more

The tsserver setting specifies additional options related to the internal tsserver process, like tracing and logging.

  1. ``` ts
  2. interface TsserverOptions {
  3.     /**
  4.      * The path to the directory where the `tsserver` log files will be created.
  5.      * If not provided, the log files will be created within the workspace, inside the `.log` directory.
  6.      * If no workspace root is provided when initializating the server and no custom path is specified then
  7.      * the logs will not be created.
  8.      *
  9.      * @default undefined
  10.      */
  11.     logDirectory?: string;
  12.     /**
  13.      * Verbosity of the information logged into the `tsserver` log files.
  14.      *
  15.      * Log levels from least to most amount of details: `'terse'`, `'normal'`, `'requestTime`', `'verbose'`.
  16.      * Enabling particular level also enables all lower levels.
  17.      *
  18.      * @default 'off'
  19.      */
  20.     logVerbosity?: 'off' | 'terse' | 'normal' | 'requestTime' | 'verbose';
  21.     /**
  22.      * The path to the `tsserver.js` file or the typescript lib directory. For example: `/Users/me/typescript/lib/tsserver.js`.
  23.      */
  24.     path?: string;
  25.     /**
  26.      * The verbosity of logging of the tsserver communication.
  27.      * Delivered through the LSP messages and not related to file logging.
  28.      *
  29.      * @default 'off'
  30.      */
  31.     trace?: 'off' | 'messages' | 'verbose';
  32.     /**
  33.      * Whether a dedicated server is launched to more quickly handle syntax related operations, such as computing diagnostics or code folding.
  34.      *
  35.      * Allowed values:
  36.      * - auto: Spawn both a full server and a lighter weight server dedicated to syntax operations. The syntax server is used to speed up syntax operations and provide IntelliSense while projects are loading.
  37.      * - never: Don't use a dedicated syntax server. Use a single server to handle all IntelliSense operations.
  38.      *
  39.      * @default 'auto'
  40.      */
  41.     useSyntaxServer?: 'auto' | 'never';
  42. }
  43. ```

The preferences object is an object specifying preferences for the internal tsserver process. Those options depend on the version of Typescript used but at the time of writing Typescript v4.4.3 contains these options:

  1. ``` ts
  2. interface UserPreferences {
  3.     /**
  4.      * Glob patterns of files to exclude from auto imports. Requires using TypeScript 4.8 or newer in the workspace.
  5.      * Relative paths are resolved relative to the workspace root.
  6.      * @since 4.8.2
  7.      */
  8.     autoImportFileExcludePatterns: [],
  9.     disableSuggestions: boolean;
  10.     quotePreference: "auto" | "double" | "single";
  11.     /**
  12.      * If enabled, TypeScript will search through all external modules' exports and add them to the completions list.
  13.      * This affects lone identifier completions but not completions on the right hand side of `obj.`.
  14.      */
  15.     includeCompletionsForModuleExports: boolean;
  16.     /**
  17.      * Enables auto-import-style completions on partially-typed import statements. E.g., allows
  18.      * `import write|` to be completed to `import { writeFile } from "fs"`.
  19.      */
  20.     includeCompletionsForImportStatements: boolean;
  21.     /**
  22.      * Allows completions to be formatted with snippet text, indicated by `CompletionItem["isSnippet"]`.
  23.      */
  24.     includeCompletionsWithSnippetText: boolean;
  25.     /**
  26.      * If enabled, the completion list will include completions with invalid identifier names.
  27.      * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`.
  28.      */
  29.     includeCompletionsWithInsertText: boolean;
  30.     /**
  31.      * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled,
  32.      * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined
  33.      * values, with insertion text to replace preceding `.` tokens with `?.`.
  34.      */
  35.     includeAutomaticOptionalChainCompletions: boolean;
  36.     /**
  37.      * If enabled, completions for class members (e.g. methods and properties) will include
  38.      * a whole declaration for the member.
  39.      * E.g., `class A { f| }` could be completed to `class A { foo(): number {} }`, instead of
  40.      * `class A { foo }`.
  41.      * @since 4.5.2
  42.      * @default true
  43.      */
  44.     includeCompletionsWithClassMemberSnippets: boolean;
  45.     /**
  46.      * If enabled, object literal methods will have a method declaration completion entry in addition
  47.      * to the regular completion entry containing just the method name.
  48.      * E.g., `const objectLiteral: T = { f| }` could be completed to `const objectLiteral: T = { foo(): void {} }`,
  49.      * in addition to `const objectLiteral: T = { foo }`.
  50.      * @since 4.7.2
  51.      * @default true
  52.      */
  53.     includeCompletionsWithObjectLiteralMethodSnippets: boolean;
  54.     /**
  55.      * Indicates whether {@link CompletionEntry.labelDetails completion entry label details} are supported.
  56.      * If not, contents of `labelDetails` may be included in the {@link CompletionEntry.name} property.
  57.      * Only supported if the client supports `textDocument.completion.completionItem.labelDetailsSupport` capability
  58.      * and a compatible TypeScript version is used.
  59.      * @since 4.7.2
  60.      * @default true
  61.      */
  62.     useLabelDetailsInCompletionEntries: boolean;
  63.     /**
  64.      * Allows import module names to be resolved in the initial completions request.
  65.      * @default false
  66.      */
  67.     allowIncompleteCompletions: boolean;
  68.     importModuleSpecifierPreference: "shortest" | "project-relative" | "relative" | "non-relative";
  69.     /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
  70.     importModuleSpecifierEnding: "auto" | "minimal" | "index" | "js";
  71.     allowTextChangesInNewFiles: boolean;
  72.     lazyConfiguredProjectsFromExternalProject: boolean;
  73.     /**
  74.      * Indicates whether imports should be organized in a case-insensitive manner.
  75.      *
  76.      * Default: `"auto"`.
  77.      */
  78.     organizeImportsIgnoreCase: "auto" | boolean;
  79.     /**
  80.      * Indicates whether imports should be organized via an "ordinal" (binary) comparison using the numeric value
  81.      * of their code points, or via "unicode" collation (via the
  82.      * [Unicode Collation Algorithm](https://unicode.org/reports/tr10/#Scope)) using rules associated with the locale
  83.      * specified in {@link organizeImportsCollationLocale}.
  84.      *
  85.      * Default: `"ordinal"`.
  86.      */
  87.     organizeImportsCollation: "ordinal" | "unicode";
  88.     /**
  89.      * Indicates the locale to use for "unicode" collation. If not specified, the locale `"en"` is used as an invariant
  90.      * for the sake of consistent sorting. Use `"auto"` to use the detected UI locale.
  91.      *
  92.      * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`.
  93.      *
  94.      * Default: `"en"`
  95.      */
  96.     organizeImportsCollationLocale: string;
  97.     /**
  98.      * Indicates whether numeric collation should be used for digit sequences in strings. When `true`, will collate
  99.      * strings such that `a1z < a2z < a100z`. When `false`, will collate strings such that `a1z < a100z < a2z`.
  100.      *
  101.      * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`.
  102.      *
  103.      * Default: `false`
  104.      */
  105.     organizeImportsNumericCollation: boolean;
  106.     /**
  107.      * Indicates whether accents and other diacritic marks are considered unequal for the purpose of collation. When
  108.      * `true`, characters with accents and other diacritics will be collated in the order defined by the locale specified
  109.      * in {@link organizeImportsCollationLocale}.
  110.      *
  111.      * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`.
  112.      *
  113.      * Default: `true`
  114.      */
  115.     organizeImportsAccentCollation: boolean;
  116.     /**
  117.      * Indicates whether upper case or lower case should sort first. When `false`, the default order for the locale
  118.      * specified in {@link organizeImportsCollationLocale} is used.
  119.      *
  120.      * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. This preference is also
  121.      * ignored if we are using case-insensitive sorting, which occurs when {@link organizeImportsIgnoreCase} is `true`,
  122.      * or if {@link organizeImportsIgnoreCase} is `"auto"` and the auto-detected case sensitivity is determined to be
  123.      * case-insensitive.
  124.      *
  125.      * Default: `false`
  126.      */
  127.     organizeImportsCaseFirst: "upper" | "lower" | false;
  128.     providePrefixAndSuffixTextForRename: boolean;
  129.     provideRefactorNotApplicableReason: boolean;
  130.     allowRenameOfImportPath: boolean;
  131.     includePackageJsonAutoImports: "auto" | "on" | "off";
  132.     /**
  133.      * Preferred style for JSX attribute completions:
  134.      * - `"auto"` - Insert `={}` or `=\"\"` after attribute names based on the prop type.
  135.      * - `"braces"` - Insert `={}` after attribute names.
  136.      * - `"none"` - Only insert attribute names.
  137.      * @since 4.5.2
  138.      * @default 'auto'
  139.      */
  140.     jsxAttributeCompletionStyle: "auto" | "braces" | "none";
  141.     displayPartsForJSDoc: boolean;
  142.     generateReturnInDocTemplate: boolean;

  143.     includeInlayParameterNameHints: "none" | "literals" | "all";
  144.     includeInlayParameterNameHintsWhenArgumentMatchesName: boolean;
  145.     includeInlayFunctionParameterTypeHints: boolean,
  146.     includeInlayVariableTypeHints: boolean;
  147.     /**
  148.      * When disabled then type hints on variables whose name is identical to the type name won't be shown. Requires using TypeScript 4.8+ in the workspace.
  149.      * @since 4.8.2
  150.      * @default false
  151.      */
  152.     includeInlayVariableTypeHintsWhenTypeMatchesName: boolean;
  153.     includeInlayPropertyDeclarationTypeHints: boolean;
  154.     includeInlayFunctionLikeReturnTypeHints: boolean;
  155.     includeInlayEnumMemberValueHints: boolean;
  156. }
  157. ```

From the preferences options listed above, this server explicilty sets the following options (all other options use their default values):

  1. ``` js
  2. {
  3.     allowIncompleteCompletions: true,
  4.     allowRenameOfImportPath: true,
  5.     allowTextChangesInNewFiles: true,
  6.     displayPartsForJSDoc: true,
  7.     generateReturnInDocTemplate: true,
  8.     includeAutomaticOptionalChainCompletions: true,
  9.     includeCompletionsForImportStatements: true,
  10.     includeCompletionsForModuleExports: true,
  11.     includeCompletionsWithClassMemberSnippets: true,
  12.     includeCompletionsWithObjectLiteralMethodSnippets: true,
  13.     includeCompletionsWithInsertText: true,
  14.     includeCompletionsWithSnippetText: true,
  15.     jsxAttributeCompletionStyle: "auto",
  16.     providePrefixAndSuffixTextForRename: true,
  17.     provideRefactorNotApplicableReason: true,
  18. }
  19. ```

workspace/didChangeConfiguration


Some of the preferences can be controlled through the workspace/didChangeConfiguration notification. Below is a list of supported options that can be passed. Note that the settings are specified separately for the typescript and javascript files so [language] can be either javascript or typescript.

  1. ``` ts
  2. // Formatting preferences
  3. [language].format.baseIndentSize: number;
  4. [language].format.convertTabsToSpaces: boolean;
  5. [language].format.indentSize: number;
  6. [language].format.indentStyle: 'None' | 'Block' | 'Smart';
  7. [language].format.insertSpaceAfterCommaDelimiter: boolean;
  8. [language].format.insertSpaceAfterConstructor: boolean;
  9. [language].format.insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean
Last Updated: 2023-09-03 17:10:52