typescript ストリングリテラル(String literal)型を定義する

typescript ストリングリテラル(String literal)型を定義する

typescriptで、ストリングリテラル(String literal)型を定義するサンプルコード記述してます。typescriptのバージョンはVersion 4.1.2となります。

環境

  • OS windows10 64bit
  • typescript Version 4.1.2

ストリングリテラル型定義

ストリングリテラル型を使用すると、指定した文字列のみを許可することが可能です。

type str = 'a' | 'b' | 'c';

let s: str

s = 'a'; // 文字列 a,b,cは代入可能
s = 'b'; // 文字列 a,b,cは代入可能

s = 'd'; // dを代入しようとするとエラーになります
// error TS2322: Type '"d"' is not assignable to type 'str'.

数値も使用することが、可能です。

type num = 1 | 2 | 3 | 4 | 5;

let n: num;

n = 1;

n = 6;
//  error TS2322: Type '6' is not assignable to type 'num'.