蓝色天空.知识 · 实践 · 创造
我的收藏
TypeScript 教程目录 72章
课程介绍
TypeScript / LEARN BY DOING

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;类继承、接口契约和组合对象应按职责选择,而不是为了层级数量。

完整核心源码与验证目标

含完整源码 · 11 行
展开查看收起
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));

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

  • 小白喵喵、旺财汪汪、动物发出声音
  • 圆描述与78.54
  • 矩形20、半径3的圆28.27;均来自对应实例实现

本章附件与实例包

下载课程关联工程包:TypeScript

课程关联工程包(登记关联72章) · 含当前章节或实例 · mbskycom202611a325.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

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

查看参考解答

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

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习