zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Exclude 的实现

2023-02-18 16:37:30 时间

# 动手实现 Exclude

最近在刷题,碰到了一个手动实现Excelude<T, U>的题目

原题地址:https://github.com/type-challenges/type-challenges/blob/main/questions/00043-easy-exclude/README.zh-CN.md (opens new window)

也欢迎大家和我一起共同学习!

# Exclude 的作用

在 ts 中,我们能够使用 Exclude<T,U> 这个工具,帮助我们把 T 类型当中属于 U 类型的部分去除后得到一个新的类型,ts 已经自己提供了,使用方式如下:

type myType = Exclude<'a' | 'b' | 'c', 'a'>

得到的 myType'a'|'b',明白 Exclude 的作用以后就可以自己手动实现一个了

# MyExclude 的实现

首先我们使用 js 来实现,代码如下,假设 Exclude 为一个函数

/**
 * T: ['a', 'b', 'c']
 * U: ['a']
 */
function MyExclude(T: any[], U: any[]) {
  const result = []
  for (let i = 0; i < T.length; i++) {
    const temp = T[i]
    if (!U.includes(temp)) {
      result.push(temp)
    }
  }
  return result
}

const T = ['a', 'b', 'c']
const U = ['a']
MyExclude(T, U) // ['b', 'c']

有上述的函数代码可以知道,在获得最终类型的时候,必定会经过循环,在 ts 中使用 extends 关键字可以实现,ts 的代码实现如下 :

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

原理如下图所示:

T

U

Result

a

a

never

b

a

b

c

a

c

T 当中的每一项,取出与 U 当中的每一项进行比较,相同返回 never,不同则返回 T 当中的项