Typescript类型体操 - IsUnion
题目
中文
实现一个 IsUnion
类型, 接受输入类型 T
, 并返回 T
是否为联合类型.
type case1 = IsUnion<string>; // false
type case2 = IsUnion<string | number>; // true
type case3 = IsUnion<[string | number]>; // false
English
Implement a type IsUnion
, which takes an input type T
and returns whether T
resolves to a union type.
For example:
type case1 = IsUnion<string>; // false
type case2 = IsUnion<string | number>; // true
type case3 = IsUnion<[string | number]>; // false
答案
type IsUnion<T, K = T> = [T] extends [never]
? false
: T extends T
? [Exclude<K, T>] extends [never]
? false
: true
: false;