Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript generic with conditional evaluates union types separately

I am trying to create a TypeScript type that will represent either a VoidFunction or a function with a single parameter based on a provided generic.

Using a conditional, the type looks like this:

type VoidFunctionOrWithParams<Params> = Params extends void
    ? VoidFunction
    : (params: Params) => void;

An example usage might look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type WithStringParams = VoidFunctionOrWithParams<'one' | 'two'>;

Expected Result Type

(params: 'one' | 'two') => void

Actual Result Type

((params: "one") => void) | ((params: "two") => void)

Why does TypeScript interpret this as two separate functions with no overlap? Is there a way around this? What I really want is one function type where params could be any of the values in the union – not different function types.

>Solution :

You are seeing the effects of conditional distributive types here. To avoid distribution, you can wrap the generic type in a tuple.

type VoidFunctionOrWithParams<Params> = [Params] extends [void]
    ? VoidFunction
    : (params: Params) => void;

type WithStringParams = VoidFunctionOrWithParams<'one' | 'two'>;
// type WithStringParams = (params: "one" | "two") => void

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading