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>
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
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.
T...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.