Tuple Includes Types Answer Membership
Answer compile-time membership questions with a recursive Includes type over literal tuples, including a negative uppercase case.
Code
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);Output
Captured from a sandboxed run of this snippet in the build pipeline.
dark: true
beta: true
legacy: false
uppercase: false
wide match: trueUsing it
The demo output is labeled (dark:, beta:, legacy:), so every printed line can be matched to the operation behind it.
Output is labeled for readability — expect lines prefixed with dark:, beta:, legacy:.
Key statements
const hasLegacy: Includes<Flags, 'legacy'> = false;
Interactive Tools for This Topic
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do.
Report a problem with this exampleOpens a pre-filled issue on GitHub.