Typescript generic parameters that extends exclusive unions
There is a proposed feature that would allow you to tell the compiler that T
is one of a number of types instead of a union of them. The issue is marked as in discussion, so maybe add a +1 for it.
In the meantime we can force the compiler to give us an error if T
is a union using conditional types:
type Any = "A" | "B"
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
type NoUnion<T, TError> = [T] extends [UnionToIntersection<T>] ? {} : TError
type d = NoUnion<Any, "">
const fn = <T extends Any>(arg: T[] & NoUnion<T, "Must be A or B not a union">) => { }
fn(null as "A"[])
fn(null as "B"[])
fn(null as ("A" | "B")[]) //error Type 'Any[]' is not assignable to type '"Must be A or B not a union"'