Open1

TypeScript 型パズル置き場

じょうげんじょうげん
  • タプルから特定の型に一致するものを絞り込んだり、除外したりするユーティリティ型
type FilterTuple<T extends unknown[], Condition> = T extends [infer First, ...infer Rest]
 ? First extends Condition
  ? [First, ...FilterTuple<Rest, Condition>]
  : FilterTuple<Rest, Condition>
 : [];

type ExcludeTuple<T extends unknown[], Condition> = T extends [infer First, ...infer Rest]
  ? First extends Condition
    ? ExcludeTuple<Rest, Condition>
    : [First, ...ExcludeTuple<Rest, Condition>]
  : [];

// 使用例
type OriginalTuple = [1, 'hello', 2, 'world', 3];
type FilteredTuple = FilterTuple<OriginalTuple, number>; // [1, 2, 3]
type ExcludedTuple = ExcludeTuple<OriginalTuple, number>; // ['hello', 'world']