#Why does TypeScript type conditional affect result of its branch?

1 messages · Page 1 of 1 (latest)

cedar oyster
#

I'm making a conditional type using the ?operator in TypeScript. Based on a condition I want the type to be two different types. When doing this, I found, that the condition affects the branches.

The MRE is here:

type Type1<O> = O extends never ? unknown : (undefined extends O ? 1 : 2);
type a = Type1<string | undefined>

type Type2<O> = undefined extends O ? 1 : 2;
type b = Type2<string | undefined>

or in TS Playground - (https://www.typescriptlang.org/play?ssl=6&ssc=1&pln=1&pc=1#code/C4TwDgpgBAKuEEYA8B5AfFAvFFUIA9gIA7AEwGcpiIA3CAJygH4oBXYga2IHsB3YqAC4oACnakIAMwCW1UnkIkKOZlARCoAJgCUAbgBQoSFACGWWPGTlg9WQHMoAHzZkpsiKTT7D8C5E2oGNjibnIKRGSUuCzqwpoGRtAARuZw-kjWtsQOziEycl5AA).

I would expect a and b to be the same, as the condition O extends never should never be true, unless O is never. This is however not the case as type a = 1 | 2 and type b = 1;

I cannot think of a reason, why the type union would be present, unless the condition in Type1 somehow iterates over the string | undefined uninon.

Why is this the case? How can I work around this, if I want a to be only 1?

here is the matching StackOverflow question: https://stackoverflow.com/questions/77075582/why-does-typescript-type-conditional-affect-result-of-its-branch

tribal ocean
#

you might want to read about Distributive Conditional Types

#

!hb Distributive Conditional Types