在开发过程中,会经常使用extends关键字,其在不同的使用场景下表现出的类型特性是不一样的。
一、ES6中的extends -- 继承
在ES6的class语法中,通过extends关键字完成类的继承;通过继承,子类拥有父类的属性和方法。
class Animal {
eat(){
console.log('animal eat')
}
}
class Cat extends Animal {
mew(){
console.log('cat mew mew mew')
}
}
const tommy = new Cat()
// 'animal eat'
tommy.eat();
// 'cat mew mew mew'
tommy.mew();
二、TS中的extends
2.1 接口继承
接口继承是ts中extends关键字最常用的方式,其功能和class的继承类似。
interface Animal {
name:string;
eat:()=>void
}
interface Cat extends Animal {
mew:()=>void
}
const tommy:Cat = {
name:'tommy',
eat:()=>{console.log('cat eat')},
mew:()=>{console.log('cat mew mew mew')}
}
2.2 条件类型
在程序中,我们有时需要根据不同的输入参数类型会产生不同的输出类型;条件类型可以帮助我们描述输入类型和输出类型之间的关系。
条件类型的形式看起来类似于JS中的三目运算符:SomeType extends OtherType ? TrueType : FalseType;
如果extends左侧的类型可以赋值给extends右侧的类型,则返回TrueType,否则返回FalseType
interface Animal {
name:string;
eat:()=>void
}
interface Cat extends Animal {
mew:()=>void
}
type Example1 = Cat extends Animal ? number : string;
// type Example1 = number
type Example2 = RegExp extends Animal ? number : string;
// type Example2 = string
2.3 泛型约束
默认的泛型是可以接收任意类型的,有时我们需要约束泛型的可接收类型。我们可以创建一个interface作为约束,然后通过extends关键字表示约束;
interface Lengthwise {
length: number;
}
function loggingIdentity<Type extends Lengthwise>(arg: Type): Type {
console.log(arg.length); // Now we know it has a .length property, so no more error
return arg;
}
// error: Argument of type 'number' is not assignable to parameter of type 'Lengthwise'.
loggingIdentity(3);
// ok
loggingIdentity({ length: 10, value: 3 });