class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
sayHi() {
return `My name is ${this.name}`;
}
}
class Cat extends Animal{
constructor(name: string) {
super(name); // 呼叫父類別的 constructor(name)
console.log(this.name);
}
sayHi() {
return 'Meow, ' + super.sayHi(); // 呼叫父類別的 sayHi()
}
sayMeow(){
return 'Meow~';
}
}
let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom
定義好 Interface 後,我們可以在 Class 關鍵字後方加上 implements + YourInterface 進行實作:
class Cat extends Animal implements cat{
constructor(name: string) {
super(name); // 呼叫父類別的 constructor(name)
console.log(this.name);
}
sayHi() {
return 'Meow, ' + super.sayHi(); // 呼叫父類別的 sayHi()
}
sayMeow(){
return 'Meow~';
}
}
let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom
此外,我們同樣可以讓一個 Class 實現多個 Interface:
interface Meow{
sayMeow(): any;
}
interface Hi{
sayHi() :any;
}
class Cat extends Animal implements Meow, Hi{
constructor(name: string) {
super(name); // 呼叫父類別的 constructor(name)
console.log(this.name);
}
sayHi() {
return 'Meow, ' + super.sayHi(); // 呼叫父類別的 sayHi()
}
sayMeow(){
return 'Meow~';
}
}
let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom
筆者在這邊對於介面的定義比較隨性一些,實際上應該不會有人把這兩個 Function 拿出來獨立描述才是。
error: TS2564 [ERROR]: Property 'x' has no initializer and is not definitely assigned in the constructor.
x: number;
^
TS2564 [ERROR]: Property 'y' has no initializer and is not definitely assigned in the constructor.
y: number;
答案是 No ,我在 TypeScript 的官方文件的最尾端仍然有看到這奇特的用法,有趣的是,在按下範例程式碼上的 Try it! 後,我一樣可以從官方的線上 Compiler 看到一模一樣的錯誤訊息。
因此,我也順手試了幾個範例程式碼,也是多多少少有會有 Error 提示....
筆者都搞不清楚是我自己不會使用 TypeScript ,還是它本身真的有問題了...
最後,我在 Class 中定義了建構者函式便能順利執行了:
class Point {
x: number;
y: number;
constructor(x: number,y:number){
this.x = x;
this.y = y;
}
}
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};
只是...這樣真的有意義嗎 XD
抽象類別
最後, TypeScript 支持抽象類別,至於什麼是抽象類別呢?
簡單來說,就是無法被建構出實例的 Class 。
不過,它仍然可以使用建構者函式: constructor :
abstract class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
sayHi() {
return `My name is ${this.name}`;
}
}
在加上 abstract 以後, Animal 類別就只剩下繼承用途了:
abstract class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
sayHi() {
return `My name is ${this.name}`;
}
}
class Cat extends Animal{
constructor(name: string) {
super(name); // 呼叫父類別的 constructor(name)
console.log(this.name);
}
sayHi() {
return 'Meow, ' + super.sayHi(); // 呼叫父類別的 sayHi()
}
sayMeow(){
return 'Meow~';
}
}
let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom