わいの日記

ありがちエンジニアブログ

TypeScriptいろいろ(型、継承、Interface、Singleton)

整理整理

Interface 継承

interface IFather {
    fatherName: string // おとんの名前をstring型
}

interface IMother {
    motherName: string // おかんの名前をstring型
}

// IFatherとIMotherを継承するIChildrenを定義
interface IChildren extends IFather, IMother {
    name: string
   age?: number // ? は任意項目
}

const child = <IChildren>{
    fatherName: 'tetsu',
    motherName: 'yoshie',
    name: 'chie'
   // age は任意なので設定しなくてもよい
}

関数にもinterfaceを
引数と返り値に型付けを

interface ICalc {
    (value: number): number;
}

const calcDouble: ICalc = (value: number) => value * 2

Singleton

class Person {
    private static _instance: Person;
    private constructor() { }
    private _name: string;

    static getInstance(): Person {
        if (!Person._instance) {
            Person._instance = new Person();
        }
        return Person._instance
    }

    get name(): string {
        return this._name
    }

    set name(name: string) {
        this._name = name; 
    }

}
const person = Person.getInstance();
console.log(person)
person.name = 'wai'
console.log(person.name)

継承の注意点

// IMyArrayを定義する
interface IMyArray {
    // indexがnumberでその値がstring型
    [index: number]: string;
}

// IMyArray型の配列を定義する
const days: IMyArray = ["Mon", "Tue"]

days.push("Wed") //IMyArrayにpushメソッドなんてないとエラーが起こる

解決策

// IMyArrayがArray型を継承するようにする
interface IMyArray extends Array<string> {
    [index: number]: string;
}

const days: IMyArray = ["Mon", "Tue"]

days.push("Wed") 

ふむふむ
もっと勉強しないと

amzn.to

amzn.to