typescript继承
继承使用关键字 extends
。
实例
index.html
文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>typescript demo</title>
</head>
<body>
<script src="hello.js"></script>
</body>
</html>
修改 hello.ts
文件:
class Rectangle {
area: number;
private color: string;
constructor (public name: string, width: number, height: number){
this.area = width * height
this.color = 'red';
}
sayHi() {
console.log('this.color',this.color)
return 'I am ' + this.name + ' the color is '+ this.color + ' the area is ' + this.area + ' cm squares.'
}
}
var rec = new Rectangle('suq',50,60);
console.log('rec.sayHi()', rec.sayHi());
console.log('rec.area', rec.area);
console.log('rec.name', rec.name);
console.log('rec.width', rec.width);
console.log('rec.height', rec.height);
console.log('rec.color', rec.color);
class Rectg extends Rectangle {
volume: number;
constructor (public name: string, width: number, height: number, length: number){
super(name,width,height);
this.volume = length * this.area
}
sayHi() {
return 'I am ' + this.name + ' the volume is '+ this.volume + ' cm cube.'
}
sayHello() {
return super.sayHi()
}
}
var cuba = new Rectg('cuba',50,60,30);
console.log('cuba.sayHi()', cuba.sayHi());
console.log('cuba.sayHello()', cuba.sayHello());
接下来,打开命令行,使用 tsc
命令编译 hello.ts
文件:
$ tsc hello.ts
编译结果:
hello.ts:19:30 - error TS2339: Property 'width' does not exist on type 'Rectangle'.
19 console.log('rec.width', rec.width);
~~~~~
hello.ts:20:31 - error TS2339: Property 'height' does not exist on type 'Rectangle'.
20 console.log('rec.height', rec.height);
~~~~~~
hello.ts:21:30 - error TS2341: Property 'color' is private and only accessible within class 'Rectangle'.
21 console.log('rec.color', rec.color);
~~~~~
Found 3 errors in the same file, starting at: hello.ts:19
然后,打开 index.html
,可以看到如下打印信息:
派生类Rectg
说明:
- 派生类
Rectg
继承了Rectangle
类,也继承了Rectangle
类的color
属性 - 构造函数中,
super
方法调用了 基类Rectangle
的构造函数,传递了参数name
,width
, 和height
值。 继承允许复用Rectangle
类的代码,所以可以通过继承area
属性来计算this.volume
。 Rectg
的sayHello()
方法重写基类的实现。
sayHi()
方法通过使用super
关键字直接返回了基类的sayHi()
方法。
参考文档:
https://www.runoob.com/w3cnote/getting-started-with-typescript.html
https://www.runoob.com/typescript/ts-tutorial.html
https://www.tslang.cn/