プリミティブ型したい
文字列したい(string)
1// string
2const name = "Taro"
1const name: string = "Taro";
""(もしくは''、 ``)で囲んだ文字の並びがstring型になります。
数値したい(number)
1// number
2const count = 42;
3const price = 3.14;
1const count: number = 42;
2const price: number = 3.14;
整数・小数を問わず、数値はすべてnumber型として扱われます。
JavaScriptには整数専用の型はありません。
真偽値したい(boolean)
1const isActive = true;
1const isActive: boolean = true;
trueまたはfalseのいずれかの値をとる型です。
未定義したい(undefined)
1let value;
2console.log(value); // -> undefined
1let value: number | undefined;
宣言だけして値を代入していない変数はundefinedになります。
明示的にundefinedを代入することもできます。
nullしたい(null)
1const data = null;
1const data: string | null = null;
「値が存在しない」ことを意図的に表す型です。
undefinedが「未代入」であるのに対して、nullは「値がないことを明示的に代入した」状態を表します。
BigIntしたい(bigint)
1const big = 12345678901234567890n;
1const big: bigint = 12345678901234567890n;
number型では正確に扱えないほど大きな整数を扱いたいときに使う型です。
数値リテラルの末尾にnを付けるとbigintになります。
シンボルしたい(symbol)
1const id = Symbol("id");
1const id: symbol = Symbol("id");
Symbol()を呼ぶたびに、常に一意な値が生成される型です。
オブジェクトのプロパティ名を他と衝突させたくない場合などに使います。
リテラル型したい
1let status: "success" | "error";
2status = "success"; // OK
3status = "fail"; // Error
リテラル型(literal types)は、
「値そのものを型」として扱うTypeScriptの仕組みです。
文字列(string)以外にも数値(number)や真偽値(boolean)をリテラル型として使えます。
上記のサンプルではstatusの値として"success"と"error"がOKとなります。
それ以外の値を代入するとエラーになります。
1type Status = "idle" | "loading" | "success" | "error";
2
3let status: Status = "idle";
リテラル型で指定する値が多い場合は、typeで新しく型名を作成するほうがよいかもしれません。