14
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeScript で enum を union に変換する方法

Last updated at Posted at 2022-06-14

やりたい事

こんな感じの enum があったとして、これを union に変換したい。

enum PenguinEnum  {
  EMPEROR = '皇帝ペンギン',
  ADELE = 'アーデリーペンギン',
  HUMBOLDT = 'フンボルトペンギン'
}

やり方

どうやら TypeScript v4.1 で追加されたテンプレートリテラル型を利用することで、 union 型に変換する事ができるようです。

enum PenguinEnum  {
  EMPEROR = '皇帝ペンギン',
  ADELE = 'アーデリーペンギン',
  HUMBOLDT = 'フンボルトペンギン'
}

//'皇帝ペンギン' | 'アーデリーペンギン' | 'フンボルトペンギン' 
type penguin = `${PenguinEnum}`

//'EMPEROR' | 'ADELE' | 'HUMBOLDT'
type penguinKeys = keyof typeof PenguinEnum

参考にした記事

Announcing TypeScript 4.1 - TypeScript: https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/

Typescript: string literal union type from enum - Stack Overflow: https://stackoverflow.com/questions/52393730/typescript-string-literal-union-type-from-enum/64966647#64966647

14
5
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
14
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?