🛵

VS Codeで自動でtype-only importする

に公開

結論

以下の設定をsettings.jsonに追加する。

{
  // ...
  "typescript.preferences.preferTypeOnlyAutoImports": true,
  // ...
}

これにより型をimportする際以下のようにtypeキーワードが自動で付与される。

import type { User } from './user';

背景

BiomeのrecommendedなルールとしてuseImportTypeがあり、型をimportする際はtype-only importしないと怒られる。なおBiomeのドキュメントでもこの設定が推奨されている。

You may also want to enable the editor setting typescript.preferences.preferTypeOnlyAutoImports from the TypeScript LSP. This setting is available in Visual Studio Code. It ensures the type is used when the editor automatically imports a type.

typescript.preferences.preferTypeOnlyAutoImportsはVS Code 1.85(2023年11月リリース)で追加されている。
https://code.visualstudio.com/updates/v1_85#_prefer-using-type-for-auto-imports

type-only importはTypeScript 3.8で追加されている。type-only importすることで、型のみに使用されるインポートがコンパイル時にJavaScriptコードから完全に除去され、バンドルサイズが削減される。
https://devblogs.microsoft.com/typescript/announcing-typescript-3-8/#type-only-imports-and-exports

昔はESLintの@typescript-eslint/consistent-type-importsを用いてtype-only importするのが一般的だったっぽい。
https://qiita.com/derasado/items/20da03ea0d5dd3fceb07

GitHubで編集を提案

Discussion