0
0

More than 1 year has passed since last update.

【TypeScript】定数、型、ラベルを定義して取り出す方法(as Const + keyof typeof)

Last updated at Posted at 2023-04-26

const定義

まずは定数を定義する。以下のようにconstを使って定義する。

export const FRUIT_LIST = {
  APPLE: 'apple',
  ORANGE: 'orange',
} as const;

Type定義

次に、定数をもとに型を定義する方法。keyof typeofを使って以下のように定義する。

export type FruitType = typeof FRUIT_LIST[keyof typeof FRUIT_LIST];
// FruitType  = 'apple' | 'orange'

ラベル定義

Recordを使って、先ほど定義した型をキーとして、対応する文字列を格納。
日本語ラベルを定義できる

export const FRUIT_LABELS: Record<FruitType, string> = {
  [FRUIT_LIST.APPLE]: 'りんご',
  [FRUIT_LIST.ORANGE]: 'みかん',
};

取り出し方

最後に、上記で定義したラベルを取り出す方法をば。
以下のようにしてJSX側では取り出すことが可能

 {FRUIT_LABELS[FRUIT_LIST.apple]} // りんご
0
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
0
0