ts中extends关键字

ts中extends使用还是挺频繁的,但是在不同的场景下使用它的含义是不同的,所以在这篇文章中进行总结一下,方便理解

1.接口扩展的含义

interface Shape {
  color: string;
}

interface Square extends Shape {
  sideLength: number;
}

// Square {
//  color: string;
//  sideLength: number;
// }

const square: Square = {
  color: "red",
  sideLength: 10,
};

接口Square通过extends关键字将Shape的属性也添加到自己的接口属性里面。

2.范型约束:

function loggingIdentity<T extends {length: number}>(arg: T): T {
  console.log(arg.length);
  return arg;
}

loggingIdentity([1, 2, 3]); // 输出 3
loggingIdentity("hello"); // 输出 5
loggingIdentity(123); // 报错,因为数字类型没有 length 属性

上面的范型T需要满足有属性{lenght: number}

3.条件中使用

3.1 约束

type Duck = {
  name: string;
  occupation: string;
}
type Human = {
  name: string;
}
type Bool = Duck extends Human ? 'yes' : 'no'; // Bool => 'yes'

Human作为约束条件,Human有的属性 Duck都有 所以返回yes,(这里A extends B并不是指类型A是类型B的子集。)

3.2 extends前面是一个范型,并且当传入该参数的是联合类型时:


  type Y1 = 'x' | 'y' extends 'x' ? string : number; // number
  
  type P<T> = T extends 'x' ? string : number;
  type Y2 = P<'x' | 'y'> // "string" | "number"

上面Y1和Y2的结果大不一样,引发我们思考🤔,造成这个结果的原因就是所谓的分配条件类型(Distributive Conditional Types)

When conditional types act on a generic type, they become distributive when given a union type

对于使用extends关键字的条件类型(即上面的三元表达式类型),如果extends前面的参数是一个泛型类型,当传入该参数的是联合类型,则使用分配律计算最终的结果。分配律是指,将联合类型的联合项拆成单项,分别代入条件类型,然后将每个单项代入得到的结果再联合起来,得到最终的判断结果。

我们继续使用上面的例子进行解析:

 type P<T> = T extends 'x' ? string : number;
 type Y2 = P<'x' | 'y'> // "string" | "number"

首先"x"  extends "x"  返回"string"

接着"y"  extends "x"  返回"number"

最后Y2结果就变成了"string" | "number"了。


 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值