KarlsFriend
KarlsFriend

Reputation: 745

Get List of all types of a certain string-type

I had this typescript generated by the generateTypeScript-gradle plugin.

export type FoodUnit = "AS_NEEDED" | "G" | "KG" | "ML" | "L" | "JAR" | "CAN" | "PIECE" | "BUNCH" | "HANDFUL" | "STALK" | "SLICE" | "TABLESPOON" | "TEASPOON" | "DROP" | "CUP" | "TWIG";

Now I want to have a list of all possible units in a class.

  units:FoodUnit[] = ["AS_NEEDED", "G", "KG" .....

Is there a way to instead write

  units:FoodUnit[] = FoodUnit.values()

like I would in Java?

Upvotes: 0

Views: 59

Answers (1)

JKillian
JKillian

Reputation: 18351

Your generated code uses the type keyword and thus produces a type alias:

export type FoodUnit = "AS_NEEDED" | "G" | "KG" | "ML" | "L" | "JAR" | "CAN" | "PIECE" | "BUNCH" | "HANDFUL" | "STALK" | "SLICE" | "TABLESPOON" | "TEASPOON" | "DROP" | "CUP" | "TWIG";

Type aliases are purely compile-time constructs: they don't exist in any form in your JS code that is actually run by a browser or Node.

If you want a string-based enum construct, you can use a library like typescript-string-enums or do it yourself as documented here.

Upvotes: 1

Related Questions