現在、 JavaScript のみの Vue プロジェクトに対して TypeScript 導入を行なっています。
インストール済みのライブラリには、型情報のないもの1が存在し、以下のようなエラーが発生していました。
Could not find a declaration file for module 'ライブラリ名'. Try npm install @types/ライブラリ名 if it exists or add a new declaration (.d.ts) file containing declare module 'ライブラリ名';
dts-gen
というライブラリを用いてライブラリ名.d.ts
を作成、上記エラー解消とともに、型推論が効くようにしたまでの手順をメモとして書き残しておきます。
環境
変更差分(PR)は以下です。
Feature/dts gen sample by zakizaki-ri9 · Pull Request #75 · zakizaki-ri9/typescript-sandbox · GitHub
手順
ライブラリインストール
dts-gen
とは、Microsoft謹製 JavaScript のライブラリをベースに d.ts
を生成してくれるツールです。
今回は jp-prefecture
という日本の都道府県情報を検索できるライブラリの d.ts
を生成してみたいと思います。
これら d.ts
を作成するためのライブラリ等々を以下でインストールします。
npm i -D dts-gen jp-prefecture # TypeScript がグローバルインストールしてない場合は、以下も実行する npm i -D typescript
必要に応じて、tsconfig.json
も設定します。こだわりない場合は、以下コミットの tsconfig.json
を参考にしてください。
feat: npx dts-gen -m jp-prefecture · zakizaki-ri9/typescript-sandbox@8dee5e2 · GitHub
d.ts
生成 〜 サンプルコード記述
以下で jp-prefecture.d.ts
を生成します。
npx dts-gen -m jp-prefecture
生成後、そのままだとエラー解消&型推論できないため、以下のような形で書き換えます。
@types/jp-prefecture.d.ts
+declare module "jp-prefecture" { + const VERSION: string; -export = jp_prefecture; // 省略 - function where(type: any, attrs: any, select: any): any; + function where(type: any, attrs: any, select: any): any; }
tsconfig.json
+ "typeRoots": [ + "node_modules/@types", + "./@types" + ],
以下のようなコードを記述し、エラー解消&型推論できていればOKです。
import * as jp from "jp-prefecture" console.log({ getAllResult: jp.getAll("pref", ["id", "name"]) })
詳細なコードは以下コミットを参照してください。
feat: typing set jp-prefecture · zakizaki-ri9/typescript-sandbox@d388ed9 · GitHub
参考情報
dts-gen
以外にも dtsmake
というライブラリもあるみたいです。
- TypeScript型定義ファイルのコツと生成ツール dtsmake - Qiita
- GitHub - ConquestArrow/dtsmake: TypeScript 's type definition file (*.d.ts files) generator tool from JavaScript files.
おわり
以上です。
次は any
を潰して、以下記事を参考にDefinitelyTyped
へ型追加のPR投げてみたいなぁ...。