概念
- 在由子类生成的实例对象时,实例对象的类型既是父类的类型,也是子类的类型
实例:
class Person2{
name:string
constructor(name:string){
this.name = name
}
sayName(){
console.log(this.name);
}
}
class p1 extends Person2{
constructor(name:string){
super(name)
}
sayName(): void {
console.log(this.name);
}
}
class p2 extends Person2{
constructor(name:string){
super(name)
}
sayName(): void {
console.log(this.name);
}
}
let s1:Person2 = new p1('p1');
let s2:Person2 = new p2('p2');
s1.sayName();
s2.sayName();
function test (a:Person2,b:Person2){
console.log(a,b);
}
test(s1,s2)
- 总结:
- p1类继承至Person2类,p2类继承至Person2类
- 将s1,s2设置为Person2类型,并用其去接收子类的实例对象时,不会报错
- 限制test的传参类型为Person2类型时,将s1和s2做为实参传入函数时,不会报错