typescript 将类型元组转换为交集

xwbd5t1u  于 2023-03-31  发布在  TypeScript
关注(0)|答案(2)|浏览(131)

如何将一个类型元组同时转换为所有这些类型的交集?

type TupleToIntersection<
  Rest extends any[],
  T = Rest extends [any, ...any[]] ? Rest['0'] : never,
> = Rest extends [infer H, ...infer S] ? TupleToIntersection<S, H & T> : T

type TTest1 = TupleToIntersection<[string,any,number]> // any but should be never!

type Test1 = string & any & number   // never
type Test2 = (string & any) & number // any - what TupleToIntersection is doing

代码

kq4fsx7k

kq4fsx7k1#

如下定义TupleToIntersection可以提供您所需的内容:

type TupleToIntersection<T extends any[]> = {
  [K in keyof T]: (x: T[K]) => void
} extends {
  [K: number]: (x: infer I) => void
}
  ? I
  : never
type TTest1 = TupleToIntersection<[string,any,number]> // never
type TTest2 = TupleToIntersection<['a' | 'b', 'b' | 'c']> // b
au9on6nz

au9on6nz2#

这要简单得多,也可以与两个以上元素一起使用:

type ListToIntersection<R extends any[]> = R extends [infer H, ...infer S] ? H & ListToIntersection<S>  : unknown.

相关问题