TypeScript 5.4
2024 年 3 月 6 日に TypeScript 5.4 がリリースされました。型の改善などが行われた他、NoInfer Utility Type、Object.groupByとMap.groupBy が追加、Import Attributes を global のImportAttributesタイプでチェック出来るようになりました。
Announcing TypeScript 5.4 - TypeScript
NoInfer
NoInfer 型が追加された。これを使えば、意図しない型推論を制限することが出来る。
特定の配列にある値が含まれているかを確認する関数を考える。
tsx
function hoge<C extends string>(array: C[], value: string) {}これを型レベルで確認できるようにしたい。
tsx
function hoge<C extends string>(array: C[], value: C) {}これは型で確認できない。
tsx
hoge(["image", "video"], "audio");
// 次のような推論が行われてしまう。
type C = (typeof array)[number] | typeof value;このような場合、今までは次のようにする必要があった。
tsx
function hoge<C extends string, D extends C>(array: C[], value: D) {}
hoge(["image", "video"], "audio");
// Argument of type '"audio"' is not assignable to parameter of type '"image" | "video"'NoInfer を利用すれば、次のように記述できる。
tsx
function hoge<C extends string>(array: C[], value: NoInfer<C>) {}NoInfer は次のようにも書ける。
tsx
export type NoInfer<T> = T & { [K in keyof T]: T[K] };