🫐

Bun で `better-typescript-lib` を使用するワークアラウンド

2024/05/05に公開

What is better-typescript-lib?

https://github.com/uhyo/better-typescript-lib

ブルーベリー本でお馴染みの 🤪 先生が作成した、より意見のある TypeScript 型定義

Why better-typescript-lib?

Why don't we just fix TypeScript's built-in type definitions rather than maintaining a separate package? Actually, most of improvements in better-typescript-lib are unlikely to be accepted by TypeScript's maintainers if presented as possible improvement to TypeScript itself. This is because the improvements are too breaking to existing codebases.

A large part of any usage in TypeScript's built-in type definitions are there before the unknown type was introduced in TypeScript 3.0. Back then, there was no good way to represent “any value” in TypeScript's type system. Therefore, any was used as the best approximation. Aside from any, there are a lot of possible improvements that became possible as TypeScript evolved.

In other words, if you don't care about breaking changes (for example, you are starting a new project), you are just suffering from stale type definitions from the old days without getting any benefits from the maintained backward compatibility.

This is where better-typescript-lib comes in. It is a separate package that can be used in new projects or projects that are willing to fix type errors caused by the improvements.

後方互換性のために、any で妥協している型定義なんかをいい感じにしますよというもの。
しかもセットアップ不要。インストールするだけで良い(NPM/Yarn の場合)

Bun で動かない

素晴らしいライブラリだが、Bun で動かない。

Bun は pnpm と同じで、依存関係を自動で node_modules のルートへホイストしない。
この挙動はパッケージマネージャとしてはむしろ正しいのだが、better-typescript-lib はホイストを用いて TS のデフォルトの型を上書きするものなので、そのままでは動作しない。

pnpm にはこのようなイレギュラーへの対応手段として、public-hoist-pattern が用意されていて、better-typescript-lib もこの機能を用いることで解決する。

が、Bun には相当する機能がない。better-typescript-lib のコミッタの一人が Bun に issue を建てているが、長らく音沙汰がない

動かないのであれば、動かせば良い(?)

動かないのなら力づくで動かせば良い。
node_modules の中身を見れば分かるが、better-typescript-lib の成果物には *.d.ts しか入っていない。

パッケージマネージャとか絡むから話がややこしくなっているが、言ってしまえば better-typescript-lib は型定義ファイルの塊。

つまり tsconfig.json で読み込めば動くのだ。漢のダイレクト "include" をカマす。

tsconfig.json
{
  // ...
  "include": ["node_modules/better-typescript-lib/node_modules/@typescript/**/*.d.ts"]
  // ...
}

これで動くようになる。

導入前

😞

導入後

🤪

Let's better TypeScript life 🤪

Discussion