typescript ストリングリテラル(String literal)型を定義する
- 作成日 2021.06.06
- TypeScript
- TypeScript
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'.
-
前の記事
Ubuntu aptコマンドを高速化する 2021.06.06
-
次の記事
Ruby 配列の中で最大値のインデックス番号を求める 2021.06.06
コメントを書く