Is there a way in Typescript to constrain a generic parameter to be a union type? To illustrate my intention, below I pretend T extends UnionType
will achieve this:
function doSomethingWithUnion<T extends UnionType>(val: T) {}
doSomethingWithUnion<number | string>(...) // good
doSomethingWithUnion<number>(...) // should result in an error
I've found in another SO question (53953814) that we can check if a type is a union type:
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true
type Foo = IsUnion<string | number> // true
type Bar = IsUnion<string> // false
Which allows to, for example, to assert than a function will never return if a generic parameter is not a union type:
declare function doSomethingWithUnion<T>(val: T): [T] extends [UnionToIntersection<T>] ? never: boolean;
doSomethingWithUnion<number>(2) // never
doSomethingWithUnion<string|number>(2) // => boolean
However, I have not found a way to constrain the type itself in a similar manner.