LoginSignup
1
0

More than 3 years have passed since last update.

TypeScriptのenumについて

Last updated at Posted at 2020-07-17

個人ブログでも公開しています!
https://in-thepink.com

概要

定数を定義するのに便利な TypeScript の enum の基本を紹介します!

enum の定義・使い方

// enumを定義
enum drinkPrice {
  SMALL = 150,
  MEDIUM = 250,
  LARGE = 350,
}
const coffee = {
  price: 300,
  size: drinkPrice.MEDIUM,
};

// 出力
console.log(coffee.size); // 350

drinkPrice.MEDIUM は enum 型となります。
image2.png

再代入

readonly プロパティのため、再代入できません。
image1.png

初期値を省略した場合

// 初期化していない場合、indexの0始まりになる
enum drinkSize {
  SMALL,
  MEDIUM,
  LARGE,
}

const coffee = {
  price: 300,
  size: drinkSize.MEDIUM,
};

// 出力
console.log(coffee.size); // 2

定義された数値を基準に、インクリメントされます。
そのため、MEDIUM,LARGE は 151,152 となります。

enum drinkSize {
  SMALL = 150
  MEDIUM,
  LARGE,
}

最後に

定数を定義するのに enum は便利かと思いますが、他の記事で enum を使用しないことを薦めているものがありました。
Tree shaking ができなかったり、使い方によっては型安全ではないようです。
良いところ、悪いところ両方目を通して enum を使用すべきか検討してください!

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