【TypeScript】空を許容しないNonEmptyな配列型を定義する
const numbers1: SomeType = []; // Type Errorconst numbers2: SomeType = [1]; // Valid
TypeScriptで空を許容しない (要素数が1以上の) 配列型を定義したい。
解決法
type NonEmptyArray<T> = [T, ...T[]];
const numbers1: NonEmptyArray<number> = []; // Type Error (Source has 0 element(s) but target requires 1)const numbers2: NonEmptyArray<number> = [1]; // Valid
可変長のタプルを用いることで、少なくとも1つの要素を持つ配列型を定義できる。
function isNonEmptyArray<T>(array: T[]): array is NonEmptyArray<T> { return array.length > 0;}
const numbers = [1, 2];if (isNonEmptyArray(numbers)) console.log(numbers[0]); // Safe
空配列かを判定する関数に型ガードとして利用することになりそう。
参考