蓝色天空网mbsky.com · 知识 · 实践 · 创造TypeScript · 本地阅读预览
教程 / 前端开发 / TypeScript

TypeScript 类继承与多态

以单继承、super调用和方法重写建立多态,保留动物、图形与受保护状态的独立示例。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

子类复用基类并初始化新增字段

typescript · 阅读源码
class Animal { constructor(public name:string){} speak():string{return `${this.name}发出声音`;} }
class Dog extends Animal {
 constructor(name:string,public breed:string){super(name);}
 override speak():string{return `${this.name}汪汪`;}
}

派生构造函数使用this前必须先完成super调用。extends建立运行时原型关系,类型声明还检查签名兼容;不是通过复制一次方法字符串实现继承。override标注已有基类成员的重写,可配noImplicitOverride防止无意重名。

扩展基类描述并保持返回契约

typescript · 阅读源码
class Shape {constructor(public color:string){}describe():string{return `${this.color}图形`;}}
class Circle extends Shape {
 constructor(color:string,public radius:number){super(color);}
 override describe():string{return `${super.describe()},半径${this.radius}`;}
 area():number{return Math.PI*this.radius**2;}
}

super.describe()执行基类对应方法,调用中的this仍是当前实例;不能把super看作可任意替换的普通父类实例。构造期间调用可重写方法还要留意派生字段尚未初始化。

三个不同实现使用同一入口

typescript · 阅读源码
class Cat extends Animal {override speak():string{return `${this.name}喵喵`;}}
const animals:Animal[]=[new Cat("小白"),new Dog("旺财","金毛"),new Animal("动物")];
for(const animal of animals)console.log(animal.speak());

静态变量视角为Animal,实际派发到实例的重写实现;没有重写的基类对象仍使用基类方法。TypeScript也会按结构比较普通实例类型;多态调用并不要求每次都写instanceof。

Rectangle与Circle分别计算

typescript · 阅读源码
class Rectangle {constructor(public width:number,public height:number){}area():number{return this.width*this.height;}}
const shapes=[new Rectangle(4,5),new Circle("红色",3)];
for(const s of shapes){
 if(s instanceof Rectangle)console.log(s.area());
 else if(s instanceof Circle)console.log(s.area().toFixed(2));
}

instanceof需要运行时构造器,在跨realm、序列化/反序列化后要重新考虑。JSON解析结果不会自动恢复Rectangle原型;只有一个area字段描述也不等于真实类实例。

为子类开放所需实现

typescript · 阅读源码
class Person{constructor(protected name:string){}}
class Employee extends Person{
 constructor(name:string,private department:string){super(name);}
 introduce():string{return `${this.name}@${this.department}`;}
}

子类可使用protected name,外部接口只暴露introduce。不要为让某个调用方便就把内部状态全部public;类继承、接口契约和组合对象应按职责选择,而不是为了层级数量。

完整核心源码与验证目标

typescript · 阅读源码
export {};
class Animal{constructor(public name:string){}speak():string{return this.name+"发出声音";}}
class Dog extends Animal{constructor(name:string,public breed:string){super(name);}override speak():string{return this.name+"汪汪";}}
class Cat extends Animal{override speak():string{return this.name+"喵喵";}}
for(const animal of [new Cat("小白"),new Dog("旺财","金毛"),new Animal("动物")])console.log(animal.speak());
class Shape{constructor(public color:string){}describe():string{return this.color+"图形";}}
class Circle extends Shape{constructor(color:string,public radius:number){super(color);}override describe():string{return super.describe()+",半径"+this.radius;}area():number{return Math.PI*this.radius**2;}}
class Rectangle{constructor(public width:number,public height:number){}area():number{return this.width*this.height;}}
const circle=new Circle("红色",5);console.log("蓝色天空网",circle.describe(),circle.area().toFixed(2));
for(const s of [new Rectangle(4,5),new Circle("蓝色",3)])console.log(s instanceof Rectangle?s.area():s.area().toFixed(2));
TypeScript 类继承与多态:蓝色天空网核心实验

所需环境:固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行

当前源码 SHA256:2383c8963fb87bd225cd212cb803b520a7658f64bbcd5b02ca2f0a256ff50cce

下载本站示例源码
预期结果 · 待实际运行核验
  • 小白喵喵、旺财汪汪、动物发出声音
  • 圆描述与78.54
  • 矩形20、半径3的圆28.27;均来自对应实例实现

常见错误与边界

  • super前访问this
  • 覆写签名比基类更窄而不兼容
  • JSON对象当真实类实例
  • protected对外直接使用
  • 构造中虚调用导致未初始化

练习与解答

为什么JSON.parse得到{width:4,height:5}不能直接按instanceof Rectangle成立?

展开参考解答

反序列化只构造普通数据对象,没有调用Rectangle构造器或恢复其原型;需验证后显式new Rectangle。

规范与官方依据