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"了。