extends是ts中的关键字,在interface下可以大概理解成js中的extends,
但是还有其独有的功能:泛型类型约束。

泛型约束主要是指你定义的泛型需要符合某种特定的结构,这个结构即extends的目标。
在此基础上则可有条件类型,即符合此结构为A,否则为B的句式。

A extends B,意味着所有 B 都可以无条件被 A 替换。

示例:

  1. type test = 'hello world' extends number ? 1 : 2;
  2. // type test = 2;

我们有时候会看到这样的代码:

{
  [P in keyof T]-?: {} extends Pick<T, P> ? never : P
}

这个空 {} 对象是什么鬼?
我们来看下示例代码,这里不懂Pick的用法可以看下之前的文章。

type d1 = {} extends Pick<{color?: string}, 'color'> ? 1 : 2;  // 1
type d2 = {} extends Pick<{color: string}, 'color'> ? 1 : 2;   // 2

咦,是不是有点意思了。

我们理解成 Pick<{color?: string}, ‘color’> 是不是符合 {} 的类型,是个空对象,因为color是可选的,所以是1。

解惑 Extract**

type Extract<T, U> = T extends U ? T : never;

解惑:如果泛型 T 约束的类型符合 U 的类型,返回 T ,否则就是 never。

疑惑

type d1 = {} extends {color?: string} ? 1 : 2;  // 1
type d2 = {} extends {age: number} ? 1 : 2;       // 2

type d3 = {color?: string} extends {} ? 1 : 2;   // 1
type d4 = {color: string} extends {} ? 1 : 2;    // 1

这里看起来有点懵,也能大概理解是什么意思,但就是不能完全称述出来。。。(尴尬)
有兴趣的同学可以留言讨论。