LoginSignup
1
0

More than 3 years have passed since last update.

【備忘録】リテラルとオブジェクト型【TypeScript】

Last updated at Posted at 2020-12-23

リテラル

TypeScript,JavaScript初学者がリテラルオブジェクト型について勉強したのでメモを残す。

リテラルとは

  • JavaScript のプリミティブである値そのものである。
  • リテラルは「文字通り」という意味の単語で、ソースコードに数値や文字列をベタガキしてその値を表現する

    • Boolean 型
    • truefalseの2種類の真偽値リテラル
    • Number 型
    • 100−50のように数字を記述する数値リテラル。先頭に0xをつけると 16 進数、0oで 8 進数、obで 2 進数を表現できる。
    • BigInt 型
    • 100nのように数字の後ろにnをつけて表現する数値リテラル
    • 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
```

参考

何か指摘等ございましたら、コメントでお願いいたします。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0