TypeScript:类型兼容性-结构化(Structural)类型系统

介绍

TypeScript 采用结构化(Structural)类型系统

如果两个类 A、B,如果 B 的成员与 A 相同、甚至比 A 多,则 A(成员少的) 兼容 B(成员多的),即:成员多的 可以赋值 成员少的

看起来像鸭子,那么就是鸭子

例子

天鹅 类 的成员与 鸭子 类 相同、甚至比 鸭子 多

定义鸭子类:

class Yazi{
    type:string = "鸭子"

    gaga():void{
        console.log("嘎嘎")
    }
}

定义天鹅类:

class Tiane{
    type:string = "天鹅"

    gaga():void{
        console.log("嘎嘎")
    }
    fei():void{
        console.log("会飞")
    }
}

测试

鸭子 兼容 天鹅,即:成员多的 天鹅对象 可以赋值 成员少的 鸭子变量,看起来像鸭子,那么就是鸭子

注意:这与 C++、JAVA等开发语言不同

const obj1:Yazi = new Tiane()

console.log( obj1.type )
obj1.gaga()

错误使用1

// 成员少的,不能赋值给成员多的
const obj2:Tiane = new Yazi()

错误使用2

// 此时obj1是Yazi类型,Yazi类型没有fei() 方法,所以不能调用
obj1.fei()

原文出处:/show_1IX5MdmSBpoN.html