【TypeScript】抽象クラスの作成
こんばんは、葛の葉です。
今回は抽象クラスを作ってみます。
前回のインターフェイスをパクります。
動物という抽象クラスを作る
classを作る際の雛形を作る。共通部分を作る部分としてはインターフェイスと似ているようだけど、内部的な処理を書く場合は抽象クラス、外部へ値を渡すものをインターフェイスにするのが基本的らしい。
// Abstracts.ts export abstract class Animal { constructor( public foot: number, public length: number, public tail: boolean, public say: string, ) { } public growth(): void { this.foot = this.foot * 3; this.length = this.length * 2; }; }
インターフェイスを作る。後ほど、抽象クラスがインターフェイスを使用する。
export interface AnimalAction { // 吠えてもらう bark(): string; };
抽象クラスにインターフェイスを突っ込む
// Abstracts.ts import { AnimalAction } from "./Interfaces" export abstract class Animal implements AnimalAction { constructor( public foot: number, public length: number, public tail: boolean, private say: string, ) { } public growth(): void { this.foot = this.foot * 3; this.length = this.length * 2; }; public bark(): string { return `${this.say}と吠えるんだぜ` } }
抽象クラスはあくまで抽象クラスなので、これをそのまま使うことは出来ない。VSCodeなら警告が出る。コンパイルも通らない。
// sandbox.ts import { Animal } from "./Abstracts" let animal = new Animal(3, 5, true, "hello")
[kuzunoha@:21:03:42:~]$ tsc sandbox.ts sandbox.ts:4:14 - error TS2511: Cannot create an instance of an abstract class. 4 let animal = new Animal(3, 5, true, "hello") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Found 1 error.
クラスを作る。
import { Animal } from "./Abstracts" export class Dog extends Animal { public bark(): string { return `${this.say}だワン!!!` } }
オブジェクトを作る。
// sandbox.ts import { Dog } from "./Dog" // 日本語の変数も使えるのだよ let ポメラニアン = new Dog(3, 5, true, "がるる"); console.log(ポメラニアン.bark())
[kuzunoha@:21:23:49:~]$ node sandbox.js がるるだワン!!!