typescripttypesliterals

Generate Object of Random Value from Literal Type


I'm using a library which has a declared type as such:

type MyType = "value1" | "value2" | "value3";

I would like to create an object which holds the value of one of the possible values, randomly selected.

I was originally thinking that the MyType type was defined as an enum, but instead it is defined as above. I was referencing this answer: https://stackoverflow.com/a/55699349

Essentially, I'm looking for a generic solution to retrieving the possible values of a literal type at runtime, and then grabbing one of them at random. Here is a non-working version of what I'm looking for: TypeScript Playground

Any help is appreciated. Thanks!


Solution

  • I have learned through the comments that this is not possible, due to types being erased. More details are available here: https://www.typescriptlang.org/docs/handbook/2/basic-types.html#erased-types