ts怎么定义不为空的数组

ts分数组跟元组 [string, ...string[]] 像这样的有大佬说这是元组
ts数组方面静态检查是不是没法约束不为空的数组?

type NonEmptyTuple<T = unknown> = [T, ...T[]]; // 有大佬说这是增强元组 不是数组(说ts数组只有0或多个 想约束只有运行时才知道)

const a1: NonEmptyTuple<number> = [1, 2, 3];
console.log(a1);

const a2: NonEmptyTuple<string> = []; /* Type '[]' is not assignable to type 'NonEmptyTuple<string>'.
  Source has 0 element(s) but target requires 1.(2322) */
console.log(a2);
阅读 4.3k
1 个回答
type NonEmptyArray<T> = [T, ...T[]];

const okay: NonEmptyArray<number> = [1, 2];
const alsoOkay: NonEmptyArray<number> = [1];
const err: NonEmptyArray<number> = []; // error!