Checking for `never`

1 min to read typescript types

Playground @ TypeScript v4.9.5

Checking if some type is never may seem trivial, and one could write something like:

ts
type IsNever<T> = T extends never ? true : false

Unfortunately, it’s not gonna work as you’d expect:

ts
type A = IsNever<never> // nevertype B = IsNever<number> // falsetype C = IsNever<true> // falsetype D = IsNever<any> // boolean

Huh? The explanation boils down to the following:

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.

To make it work, you should enclose T and never in a tuple to limit type distribution:

ts
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