Use enum like literal type.

OpenAPI is a tool for schema first development. They serves several generators for typescript, like typescript-axios. Enum is supported, but not literal type. I will introduce tips using enum as a literal type.

We use AnimalType enum.

1enum AnimalType {
2 Dog = "dog",
3 Cat = "cat",

If you want to display some text depending on animal type, how do you code it?

1// React Component
2const AnimalText: React.VFC<{type: AnimalType}> = ({type}) => {
3 const text: { [key in keyof typeof AnimalType]: string } = {
4 Dog: "Dog Dog Dog",
5 Cat: "Cat Cat"
6 }
8 return <p>{text[type]}</p>

I will do like this. Then,

1// Other Component
3 <AnimalText type={AnimalType.Dog} />

AnimalText component is used like the above. I think passing AnimalType.Dog looks annoying.

If literal type is used instead of the enum, the code looks much better.

2 <AnimalText type="Dog" />

Redefine AnimalText component.

1const NewAnimalText: React.VFC<{type: keyof typeof AnimalType}> = ({type}) => {
2 const text: { [key in keyof typeof AnimalType]: string } = {
3 Dog: "Dog Dog Dog",
4 Cat: "Cat Cat"
5 }
7 return <p>{text[type]}</p>

Instead of using AnimalType directly, use keyof typeof AnimalType. Thanks to this type conversion,

NewAnimalText component can be used like the following.

2 <NewAnimalText type="Dog" />

Reconvert literal to enum

In some case, like API calling using code generated by OpenAPI, you must use enum directly.

1const li: keyof typeof AnimalType = "dog"
2const en: AnimalType = AnimalType[li]

Reconversion can be done just indexing.