Skip to content

类型体操

Array as const

将一个数组 后面添加as const 可以将数组的类型收缩 变成一个只读的元祖

ts
const arr = ['春', '夏'] as const;//把这个数组当成一个只读的常量元组,而不是普通的 string[]

TypeScript 会推断 arr 的类型为:

ts
readonly ["春", "夏"]

应用:

ts
const arr = ['春', '夏'] as const;

type ArrType = typeof arr; // readonly ["春", "夏"]

// 你可以用它来做类型推导
type Season = ArrType[number]; // "春" | "夏"