When working with TypeScript, the concept of the type Stage
... statement can be a bit perplexing as it generates a type alias rather than an actual type. Converting a string
into Stage
during runtime is unnecessary because, at that point, a Stage
essentially equates to a string
.
If you are in search of a solution that allows for easy conversion between strings and a defined set of values, consider using a TypeScript enum. This construct enables the creation of an object that facilitates seamless conversion between strings and values. Take a look at this sample test/demo routine:
import test from 'ava';
enum Stage {
First = 1,
Second = 2
}
test('Testing Stage conversion between string and number ', t=> {
const stringName = "First";
t.is(Stage.First, 1);
t.is(Stage[stringName], 1);
t.is(Stage.Second, 2);
t.is(Stage[1], "First");
t.is(Stage[2], "Second");
t.is(Stage["foo"], undefined);
t.pass();
})