serendipityApe / javascriptPromotion

资深前端必备的编码问题
3 stars 0 forks source link

实现 Exclude<T,K> #21

Open serendipityApe opened 2 years ago

serendipityApe commented 2 years ago

题目 implement Exclude<T, E>

例子

Exclude<T, K>返回一个从T中去掉能代入K的成员后的type。

请自行实现MyExclude<T, K>。

type Foo = 'a' | 'b' | 'c'

type A = MyExclude<Foo, 'a'> // 'b' | 'c'
type B = MyExclude<Foo, 'c'> // 'a' | 'b
type C = MyExclude<Foo, 'c' | 'd'>  // 'a' | 'b'
type D = MyExclude<Foo, 'a' | 'b' | 'c'>  // never

答案


//这题的核心就是extends,对于type和class两者来说,使用extends的效果是完全不同的

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


>补充

extends基础运用

type AB = X extends 'a' ? 'a' : 'b' type A=AB<'a'> //得到 A: a

当有联合类型时

type other= 'a' | 'b'; type merage = T extends 'x' ? T : other;

//传入联合类型'x' | 'y',extends会将两个类型一一验证并一同返回结果 type test= merage<'x' | 'y'>; //得到 test : 'x' | 'a' | 'b'

type other= 'a' | 'b'; type merage = T extends 'x' ? T : other;

//传入联合类型'x' | 'y',extends会将两个类型一一验证并一同返回结果 type test= merage<'y' | 'x'>; //得到 test : 'a' | 'b' | 'y'



补充内容参考链接:
https://juejin.cn/post/6844904066485583885