Checking for `never`
Checking if some type is never
may seem trivial, and one could write something like:
type IsNever<T> = T extends never ? true : false
Unfortunately, it’s not gonna work as you’d expect:
type A = IsNever<never> // nevertype B = IsNever<number> // falsetype C = IsNever<true> // falsetype D = IsNever<any> // boolean
Results are not only incorrect, but also strange. This is because union types automatically distribute in conditional types, and—since never
is basically an empty union—when distribution happens there’s nothing to distribute over, so the conditional type simply resolves to never
.
In order to fix this, you just need to enclose T
and never
in a tuple to limit type distribution:
type IsNever<T> = [T] extends [never] ? true : false
type A = IsNever<never> // truetype B = IsNever<number> // falsetype C = IsNever<true> // falsetype D = IsNever<any> // false
Voilà!