2017.11.3
2020.1.7

typeでデータ型に別名を付ける

TypeScriptではtypeを使ってデータ型に別名を付けることができます。

使い方は以下の通り。

コード(TypeScript)

nullを許容した数値型の定義。


type number2 = number | null;

let a: number2;
a = null;   // OK
a = 1;      // OK
a = "";     // NG

文字列の場合。


type Easing = "ease-in" | "ease-out" | "ease-in-out";

function animate(easing: Easing) {
    if (easing === "ease-in") {
        // ...
    }
    else if (easing === "ease-out") {
        // ...
    }
    else if (easing === "ease-in-out") {
        // ...
    }
    else {
        // ...
    }
}

インターフェースなどでも利用可能です。


interface RequestExampleAction {
    type: 'REQUEST_EXAMPLE';
}

interface ReceiveExampleAction {
    type: 'RECEIVE_EXAMPLE';
}

type knownAction = RequestExampleAction | ReceiveExampleAction;

参考リンク

TypeScript】関連記事