What's the neutral element for intersection types?

Viewed 61

For a union type, never is the neutral element, i.e. never | T = T.

Another way to see it is that for a tuple of types T=[T_1, ..., T_n], the union type T_1 | ... | T_n is given by T[number]. For an empty tuple [], [][number] yields never being the union type of an empty set of types.

Which type is the neutral element for intersection types? I.e. which built-in type N yields N & T = T for an arbitrary type T and therefore is the intersection type of an empty set?

EDIT

The rational behind my question was to build a recursive helper type to intersect all types in a tuple type. See my answer below…

1 Answers

Just figured it out myself:

For a union type, type NeutralUnion<T> = never | T is identical to T.

For an intersection type, type NeutralIntersection<T> = unknown & T is identical to T.

So, similar to building type UnionOfTupleElements<T> = T[number], we can build:

type IntersectionOfTupleElements<T extends unknown[]> = 
  T extends [infer U, ...infer V] 
    ? U & IntersectionOfTupleElements<V> 
    : unknown;

It yields:

IntersectionOfTupleElements<[]> = unknown
IntersectionOfTupleElements<[T]> = T
IntersectionOfTupleElements<[T1, T2]> = T1 & T2
Related