1

I'm very new to JS. I created a custom type called "Stage". I would like to convert strings to these types. The strings will be only ever equal one of these values exactly (first letter capitalized, written the same). I've been trying to accomplish something using .find() but this doesn't appear to be the route to go as it takes in an array. Any help is appreciated!

type Stage = 'First' | 'Second';
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
turkr
  • 43
  • 2
  • 8

1 Answers1

0

In TypeScript, the type Stage... statement is a bit confusing because it creates a type alias rather than an actual type. Converting a string into Stage at runtime is not needed because, at runtime, a Stage is a string.

A TypeScript enum may be closer to what you are looking for. It creates an object which can be used to convert to/from strings. Try something like this 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();
})

Burt_Harris
  • 6,415
  • 2
  • 29
  • 64