プリミティブ型したい
文字列したい(string)
1// string
2const name = "Taro"
1const name: string = "Taro";
数値したい(number)
1// number
2const count = 42;
3const price = 3.14;
1const count: number = 42;
2const price: number = 3.14;
真偽値したい(boolean)
1const isActive = true;
1const isActive: boolean = true;
未定義したい(undefined)
1let value;
1let value: string | undefined = undefined;
nullしたい(null)
1const data = null;
1const data: string | null = null;
BigIntしたい(bigint)
1const big = 12345678901234567890n;
1const big: bigint = 12345678901234567890n;
シンボルしたい(symbol)
1const id = Symbol("id");
1const id: symbol = Symbol("id");
リテラル型したい
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で新しく型名を作成するほうがよいかもしれません。