0

If I have a type:

type CategoryContent =
| "Physical activity"
| "Health"
| "Nutrition"
| "All categories";

 export type { CategoryContent };

How can I extract all those values into an array, but retain the type?

Right now I just have an array with the values hardcoded:

    const categories = ["Physical", "Health", "Nutrition" etc]

But when I iterate through it, the component that I'm passing it to expects the "CategoryContent" type. Not string.

How can I build the array from the actual type?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Kylie
  • 11,421
  • 11
  • 47
  • 78
  • 1
    Does this answer your question? [String Union to string Array](https://stackoverflow.com/questions/44480644/string-union-to-string-array) – jonrsharpe Jan 31 '22 at 17:53

1 Answers1

1

You cannot convert union type to array values but it is possible to do the oposite thing - convert array values to union type:

const categories = ["Physical", "Health", "Nutrition"] as const;

type CategoryContent = typeof categories[number];
  • 1
    this does not work for me - typescript still infers `CategoryContent ` as `string`. I have to add `as const` to make it work, e.g. `const categories = ["Physical", "Health", "Nutrition"] as const; ` – ABOS Jan 31 '22 at 18:21
  • 1
    @ABOS you're right. I've just edited an answer. Thanks! – Konrad Przydział Jan 31 '22 at 19:06