Skip to content

IsNever

题目

实现一个 IsNever 类型,它接受一个泛型 T

如果泛型解析为 never ,则返回 true,否则返回 false

例如:

ts
type A = IsNever<never>; // expected to be true
type B = IsNever<undefined>; // expected to be false
type C = IsNever<null>; // expected to be false
type D = IsNever<[]>; // expected to be false
type E = IsNever<number>; // expected to be false

解答

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

开始你可能会写出这样的答案:

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

你会发现这种 case 无法通过测试:

ts
type A = IsNever<never>; // check failed

为什么使用 [T] extends [never] 可以参考 #614

精选

也可以使用内置类型 Equal 来实现:

This solution seems too simple, but in my opinion, using the standard Equal function is the most correct way to create functions of the form IsNever, IsAny, IsVoid, and so on, since Equal extracts the exact internal function of type equality from TS, and does not rely on some peculiarities of types (which may hypothetically change in future versions of TS).

TS Playground.

ts
type IsNever<T> = Equal<never, T>;

Released under the MIT License.