0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

bun init で自動生成されるtsconfig.jsonで発生するBun関連APIの型エラーの解消方法

0
Posted at

Bun関連APIの型エラー

bun init を実行後に以下のコードを書くとtypeエラーが検出される。

// console.log("Hello via Bun!");

Bun.write("outout.txt", "Hello via Bun!");
~~~

このとき、"Bun"の部分に波線が表示され、以下のtypeエラーが表示される。

名前 'Bun' が見つかりません。Bun の型定義をインストールする必要がありますか?'npm i --save-dev @types/bun' を試してから、tsconfig 内の型フィールドに 'bun' を追加してください。

$ npm i --save-dev @types/bun

これはエラーが解消されなかった。
以下の1行をtsconfig.jsonに追加する事で解消。

{
  "compilerOptions": {
    ...
    "types": ["bun"],
    ...
  }
}

TypeScriptの型スキャンの挙動

通常、TypeScriptは、node_modules/@typesフォルダーにある型定義を自動で読み込む。
だが今回発生したエラーではそれが実行されないという事象。
よって、明示的にtsconfig.jsonファイルのtypesにて型定義を追加。

compilerOptoinsのtypesの定義に関するお作法

TypeScript の types オプションでは、@types/ という接頭辞を省略して書く という決まりがある。例えば、@types/bunであれば、types: ["@types/bun"]ではなくtypes: ["bun"]が正しい。
これでTypeScript は正しく node_modules/@types/bun1 を見つけ出すことができる。

Bunのグローバル変数の扱い

Bunはグローバルな変数であり、importしなくても利用できる。
だがTypeScriptはこれを認識する事ができなかった。
types: ["bun"]を定義する事で、bunという型定義ファイルを正しく認識できるようになり、エラーが解消された。

typesで明示的に型定義した場合の注意点

"types" を一度明示的に書くと、今後は 「そこに書いたもの以外は自動で読み込まないモード」 になるため、今後筆王に応じて型定義を明示的に追加していく必要がある。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?