Whenever I have a union type of strings in TypeScript, a very common thing I need to do is get an array of these string literals.
export type UserPersona =
| "entrepreneur"
| "programmer"
| "designer"
| "product_manager"
| "marketing_sales"
| "customer_support"
| "operations_hr"
I find it a bit cumbersome, but whenever I need to do this, I will create an object map, type everything out again, and then get the key can cast the type.
const userPersonaMap: { [key in UserPersona]: true } = {
entrepreneur: true,
programmer: true,
designer: true,
product_manager: true,
marketing_sales: true,
customer_support: true,
operations_hr: true,
}
export const userPersonas = Object.keys(userPersonaMap) as Array<UserPersona>
A few things I don't like about this approach:
- I have to type everything out twice.
- I have to cast the type.
- There's runtime overhead - granted, its trivial, but I do this all the time.