Can TypeScript infer type of a discriminated union via “extracted” boolean logic?

前端 未结 2 1763
暖寄归人
暖寄归人 2021-01-27 03:05

I have been using discriminated unions (DU) more frequently and have come to love them. I do however have one issue I can\'t seem to get past. If you inline a boolean check fo

2条回答
  •  有刺的猬
    2021-01-27 03:24

    There is an existing feature request at microsoft/TypeScript#12184 to allow such type guard results to be "saved" into a named value to be used later. The request is open but listed as "revisit" because there's no obvious way to implement it in a performant way. The word from the lead architect of the language is:

    This would require us to track what effects a particular value for one variable implies for other variables, which would add a good deal of complexity (and associated performance penalty) to the control flow analyzer. Still, we'll keep it as a suggestion.

    So I wouldn't expect to see such a feature in the language anytime soon, unfortunately.


    My suggestion is just to continue using your inline type check. If you have a more complex type guard situation it may be worthwhile to make a user-defined type guard function but I don't see that as an improvement for the case in your example code.


    Okay, hope that helps; good luck!

提交回复
热议问题