coding-tips

TS Union Types from Enums

A cool little typescript thing I discovered when reviewing some code.

We had this:

export default function doSomething(
  param:
    | "some-category1"
    | "some-category2"
    | "some-category3"
    | "some-category4"
    | "some-category5"
    | "some-category6"
) {
  console.log(param);
}

But we could have this:

enum descriptionCategories {
  one = "some-category1",
  two = "some-category2",
  three = "some-category3",
  four = "some-category4",
  five = "some-category5",
  six = "some-category6",
}

type descriptionCategory = `${descriptionCategories}`;

export default function doSomething(param: descriptionCategory) {
  console.log(param);
}

Cleaner, more readable, the type is reuseable across the codebase & it's easier to add new categories to.

Constanta Casino
Constanta Casino

*Fun fact* The 3 colors under the navbar are Romania's flag 🇷🇴.