雑多なブログ

音楽や語学、プログラム関連の話題について書いています

Typescript: 型エイリアス

定義方法

エイリアスtype キーワードを使って宣言する。
エイリアスは先頭を大文字で記述する。

プリミティブ型

type AgeValue = number
const age: AgeValue = 29

ユニオン型

type StringOrNull = string | null
let string_value = 'value'
string_value = null

配列型

type NumberArray = number[]
const nums: NumberArray = [1, 2, 3, 4, 5, 6]

リテラル型をユニオン型で結合

type ColorValue = 'red' | 'green' | 'yellow' | 'black' | 'white'
const color: ColorValue = 'green'

オブジェクト型

type DataValue = {
    name: string;
    age: number;
}

const data: DataValue = {
    name: 'tarou',
    age: 24
}

まとめ

リテラル型をユニオン型で結合する宣言が便利かも。