定义 NonEmptyArray 工具类型,用于确保数据非空数组。
type NonEmptyArray<T> = // 你的实现代码
const a: NonEmptyArray<string> = [] // 将出现编译错误
const b: NonEmptyArray<string> = ['Hello TS'] // 非空数据,正常使用
解法1:
type NonEmptyArray<T> = [T, ...T[]];
解法2:
type NonEmptyArray<T> = T[] & { 0: T };
解法3:
type NonEmptyArray<T> = T[]['length'] extends 0 ? never : T[]
解法4:
type NonEmptyArray<T> = {
[P in (keyof T[] & 0)]: P extends number ? T : T[][P]
}
type NonEmptyArray<T> = {
[P in number] : T
} & {0 : T}