リテラル
TypeScript,JavaScript初学者がリテラルとオブジェクト型について勉強したのでメモを残す。
リテラルとは
-
JavaScript のプリミティブである値そのものである。
-
リテラルは「文字通り」という意味の単語で、ソースコードに数値や文字列をベタガキしてその値を表現する式。
-
Boolean 型
-
trueとfalseの2種類の真偽値リテラル。
-
-
Number 型
-
100や−50のように数字を記述する数値リテラル。先頭に0xをつけると 16 進数、0oで 8 進数、obで 2 進数を表現できる。
-
-
BigInt 型
-
100nのように数字の後ろにnをつけて表現する数値リテラル。
-
-
Null 型
-
null リテラルである
nullは、プリミティブ値nullを返す。
-
null リテラルである
-
オブジェクト型
-
配列リテラル
-
[1,2,3]の形式で記述する。Arrayオブジェクトのインスタンスとして生成される。([1,2,3]って書くと配列になるよってことかな?)
-
-
オブジェクトリテラル
-
{key: value}の形式で記述する。obj.keyまたはobj[key]の 2 つの構文が利用できる。Objectオブジェクトのインスタンスとして生成される。
-
-
正規表現リテラル
-
/pattern/ig形式で記述する。正規表現パターンでの特殊文字の使い方は、ほかの言語とほぼ共通。RegExpオブジェクトのインスタンスとして生成される。
-
-
オブジェクト型は全てビルドインオブジェクトの
objectがベースになっている。
> const isBoolean = true > isBoolean.__proto__.constructor undefined [Function: Boolean] > isBoolean.__proto__.__proto__.constructor [Function: Object] > isBoolean.__proto__.__proto__.__proto__ null > > const num = 100 undefined > num.__proto__.constructor [Function: Number] > num.__proto__.__proto__.constructor [Function: Object] > > const bigInt = 100n undefined > bitInt.__proto__.constructor [Function: BigInt] > bitInt.__proto__.__proto__.constructor [Function: Object] > num.__proto__.__proto__.__proto__ null -
-
リテラル型を定義する
```typescript
// 任意のリテラル型を定義する
type Gender = `man` | `woman`;
let gender: Gender;
gender = "man"; // OK
gender = "woman"; // OK
gender = "boy"; // NG
gender = 10; // NG
```
参考
- リテラル型 - TypeScript Deep Dive 日本語版
- TypeScript の型: リテラル型を定義する (Literal types)|まくろぐ
- りあクト! TypeScript で始めるつらくない React 開発 第 3 版【Ⅰ. 言語・環境編】
何か指摘等ございましたら、コメントでお願いいたします。