实现Exclude

96 阅读1分钟

题目解析

TypeScript中,Exclude是一个内置的工具类型,用于从一个联合类型中排除另一个联合类型的成员。

示例分析

加入我们有一个联合类型T和一个联合类型U,我们希望从T中排除U中的成员

type T = 'a' | 'b' | 'c';
type U = 'a' | 'b';

// Result 的类型是 'c'
type Result = Exclude<T, U>

在这个例子中,Result的结果是c,因为ab都被排除掉了。

题解

type MyExclude<T, U> = T extends U ? never : T

type T = 'a' | 'b' | 'c'
type U = 'a' | 'b'

type Result = MyExclude<T, U>

对于联合类型T中的每个成员,如果该成员是U的子类型,则将其排除(返回nerver),否则将起保留(返回T)。

应用

interface Person {
    name: string;
    age: number;
    location: string;
}

type keys = keyof Person;
type ExcludeKeys = MyExclude<keys, 'location'>

type NewPerson = {
    [K in ExcludeKeys]: Person[K]
}

// NewPerson 类型为:
// {
//     name: string;
//     age: number;
// }

在这个例子中,我们使用MyExcludekeys中排除了location,然后使用映射类型创建了一个新的类型NewPerson,该类型只包含nameage属性。

本人是新手,如果文章中有不正确的,请各位大佬指正。