← 中文资源

简体中文版本

Tuple Includes 判断成员归属

用递归条件类型实现 Includes,在编译期判断字面量元组是否包含指定成员。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

dark: true
beta: true
legacy: false
uppercase: false
wide match: true

使用要点

  • 演示输出是带标签的(dark:、beta:、legacy:),每个操作都会留下自己的一行标注。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。

核心语句

const hasLegacy: Includes<Flags, 'legacy'> = false;

代码示例

type Includes<T extends readonly unknown[], Value> = T extends readonly [
  infer Head,
  ...infer Tail extends readonly unknown[],
]
  ? [Head] extends [Value]
    ? true
    : Includes<Tail, Value>
  : false;

type Flags = ['dark', 'compact', 'beta'];

const hasDark: Includes<Flags, 'dark'> = true;
const hasBeta: Includes<Flags, 'beta'> = true;
const hasLegacy: Includes<Flags, 'legacy'> = false;

console.log('dark:', hasDark);
console.log('beta:', hasBeta);
console.log('legacy:', hasLegacy);

// 字符串字面量区分大小写,'Dark' 不是成员
type HasUpper = Includes<Flags, 'Dark'>;
const upper: HasUpper = false;
console.log('uppercase:', upper);

// 联合值只要有一个成员匹配就返回 true
type HasWide = Includes<Flags, 'beta' | 'legacy'>;
const wide: HasWide = true;
console.log('wide match:', wide);