hrtyy.dev

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",
4}

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 }
7
8 return <p>{text[type]}</p>
9}

I will do like this. Then,

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

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.

1<div>
2 <AnimalText type="Dog" />
3</div>

Redefine AnimalText component.

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

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

NewAnimalText component can be used like the following.

1<div>
2 <NewAnimalText type="Dog" />
3</div>

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.

If you have any questions, please send an email tohoritayuya@gmail.com.