Kuzunoha-NEのブログ

プログラミングなどの勉強をしてます

【TypeScript】interfaceを作る

こんばんは、葛の葉です。

今回はTypeScriptでinterfaceオブジェクトを作ってみます。

生物に対し足の数と全長メンバー+成長というメソッド

犬というクラスとカエルというクラスを作る。

それぞれ、footというメンバーとlengthというメンバー,そしてgrowthというインスタンスメソッドを持つものとします。

AnimalInterface

// animalinterface
export interface AnimalInterface {
    foot: number;
    length: number;
    growth(): void;
};

ここでは宣言だけして、内容物は何も書きません。インターフェイスとはそのようなものです。

tsc animalinterface.ts

コンパイルをします。

インターフェイスを使ってみる。

// objects.ts
import { AnimalInterface } from "./animalinterface.js"

class Dog implements AnimalInterface {
    name:string;
};

implementsインターフェイスを使う宣言になります。今回はインターフェイスを使用していますが、その機能を無視した形を取っていますので、コンパイル時にエラーになります。

[kuzunoha@:00:31:30:~]$ tsc objects.ts
objects.ts:4:7 - error TS2420: Class 'Dog' incorrectly implements interface 'AnimalInterface'.
  Type 'Dog' is missing the following properties from type 'AnimalInterface': foot, growth

4 class Dog implements AnimalInterface {
        ~~~


Found 1 error.

interfaceを使用している場合、その使用したinterfaceオブジェクトで宣言されているメンバーやメソッドを必ず宣言しなきゃいけないものになります。

改めてインターフェイスを使って動物のクラスを作る。

object.tsという名前で以下のコードを作成する。

// objects.ts
import { AnimalInterface } from "./animalinterface";

// 犬クラス
class Dog implements AnimalInterface {
    foot: number = 4;
    length: number = 30;
    tail: boolean = true;
    growth(): void {
        this.length = 90;
    };
};

// カエルクラス
class Frog implements AnimalInterface {
    foot: number = 0;
    length: number = 3;
    tail: boolean = true;
    growth(): void {
        this.length = 5;
        this.foot = 4;
        this.tail = false;
    };
};

let inu = new Dog();
let kaeru = new Frog();
console.log(`子犬の全長:${inu.length}cm,オタマジャクシの全長:${kaeru.length}cm`)
console.log(`子犬の足の数:${inu.foot}本,オタマジャクシの足の数:${kaeru.foot}本`)
console.log("---そして月日は流れ、二匹は成長した---")
inu.growth();
kaeru.growth();
console.log(`犬の全長:${inu.length}cm,カエルの全長:${kaeru.length}cm`)
console.log(`犬の足の数:${inu.foot}本,カエルの足の数:${kaeru.foot}本`)

コンパイルして実行する。

[kuzunoha@:01:26:25:~]$ tsc objects.ts
[kuzunoha@:01:28:10:~]$ node objects.js 
子犬の全長:30cm,オタマジャクシの全長:3cm
子犬の足の数:4本,オタマジャクシの足の数:0本
---そして月日は流れ、二匹は成長した---
犬の全長:90cm,カエルの全長:5cm
犬の足の数:4本,カエルの足の数:4本

このように犬クラスとカエルクラスは共通のメンバーとメソッドを持っているけど、中身がそれぞれで異なるといった場合はインターフェイスを使用する…であってるかな?