Home > Software design >  Is is possible to iterate over the keys of a union type?
Is is possible to iterate over the keys of a union type?

Time:08-19

Is it possible to iterate over the keys of a union type in Typescript, similarly to how you can use Object.keys(someVar).map(), for example?

An example type could be:

type Status = "status_1" | "status_2" | "status_3"

An alternative I've seen is to make an immutable array and then use the typeof operator with indexing to mimic this functionality, but this seems clumsy

export const CaseStatuses = ["status_1", "status_2", "status_3"] as const;
export type CaseStatus = typeof CaseStatuses[number];

CodePudding user response:

Besides the immutable array, you can use an enum type instead of a union type. It's the only type not erased at compilation time (Enums are transpiled to an object when compiled). Then, use Object.keys()/Object.values() to iterate over it.

enum Status {
  status_1 = "status_1",
  status_2 = "status_2",
  status_3 = "status_3",
}

// Iterate over it
console.log(Object.values(Status))
  • Related