Is there a method in Typescript to restrict a generic parameter to only accept a union type? To clarify my question, I wish that T extends UnionType
would serve this purpose:
function doSomethingWithUnion<T extends UnionType>(val: T) {}
doSomethingWithUnion<number | string>(...) // valid
doSomethingWithUnion<number>(...) // should throw an error
I came across a solution in another discussion on SO (53953814) which demonstrates how to determine 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
This allows us to, for instance, ensure that a function will never return if the 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 yet discovered a way to limit the type itself in a similar fashion.