typescript的类型系统是基于结构子类型的,这种基于结构子类型的类型系统是基于组成结构的,只要具有相同类型的成员,则两种类型即为兼容的。
class Person{
name: string;
age: number;
}
class Cat{
name: string;
age: number;
}
function getPerson(p:Person){
p.name
}
let cat = new Cat();
getPerson(cat)
如果两种类型中存在差异,则可以采用接口来达到兼容
interface IFly{
fly():void;
}
class Person implements IFly{
name: string;
age: number;
study(){
}
fly(){
}
}
class Cat implements IFly{
name: string;
age: number;
catchMouse(){
}
fly(){}
}
let p1 = new Person();
let c1 = new Cat();
function fn2(arg: IFly){
arg.fly();
}
fn2(p1);
fn2(c1);