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.
我正在使用TypeScrip中的?运算符创建条件类型。根据一个条件,我希望类型是两种不同的类型。在这样做的时候,我发现这种情况会影响到树枝。
The MRE is here:
MRE在这里:
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.
或者在TS游乐场。
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
;
我希望a和b是相同的,因为O扩展的条件永远不应该为真,除非O永远不为真。然而,当类型a=1|2和类型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.
我想不出为什么会出现类型联合,除非Type1中的条件以某种方式迭代了字符串|unfined uninon。
Why is this the case? How can I work around this, if I want a
to be only 1
?
为何会是这样呢?如果我希望a仅为1,我该如何解决这个问题?
更多回答
优秀答案推荐
You are being surprised by distribution over union. Because you are using a naked type in left-hand side position in a conditional type, what you wrote is basically equivalent to writing Type1<string> | Type1<undefined>
. All you need to do is wrap the operands in square brackets.
你对分配而不是工会感到惊讶。因为您在条件类型中的左侧位置使用的是裸类型,所以您编写的内容基本上等同于编写Type1<字符串>|Type1
。您所需要做的就是将操作数括在方括号中。
更多回答
Thank you, I wasn't aware of this behavior
谢谢你,我不知道有这样的行为
Yes it's one of those things... the feature can be useful, but why they didn't add syntax for this use case is beyond me. Unexpected behaviour and huge slow-downs inducing unions are common in TS. Don't hesitate to slap square brackets on conditionals
是的,这是其中一件事……这个特性可能很有用,但我不明白他们为什么不为这个用例添加语法。意想不到的行为和导致工会的巨大减速在TS中很常见。不要犹豫,在条件句上加一个方括号
我是一名优秀的程序员,十分优秀!