其他分享
首页 > 其他分享> > Typescript类型体操 - IsUnion

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;

在线演示

标签:IsUnion,Typescript,false,true,extends,体操,case1,type
来源: https://www.cnblogs.com/laggage/p/type-challenge-is-union.html