0

I'm playing the hole day with keyof, typeof,... Is it possible to have one "source of data" for the enums and array?

for example:
- I want to have a enum type
- and an array

but I want to define one source of truth. At the moment I define 'limited','low','medium','high' 3 times and I have a lot of such "data-classes"

const myArray: string[] = [
    'limited',
    'low',
    'medium',
    'high'
];
type MyStringEnumType =
    'limited'
    | 'low'
    | 'medium'
    | 'high';

enum MyEnum
{
    Limited = 'limited',
    Low = 'low',
    Medium = 'medium',
    High = 'high'
}

type Both = MyStringEnumType | MyEnum;

let testVar1: Both = MyEnum.Limited; // works
let testVar2: Both = 'limited'; // works
console.log(myArray[0], myArray.length); // works

Thanks!

Greetings crazyx13th

7
  • Why don’t you use normal enum? Commented Sep 5, 2018 at 17:24
  • Possible duplicate of (or related to) TypeScript String Union to String Array Commented Sep 5, 2018 at 18:45
  • I'll call it a duplicate. Possible duplicate of TypeScript String Union to String Array Commented Sep 5, 2018 at 18:56
  • The above code seems to be right, is there any issue or problem? Commented Sep 5, 2018 at 18:58
  • @RezaRahmati: it's because I have a lot of such classes with some data and I wanna have "one source of truth", not double define a dataset. thx! Commented Sep 6, 2018 at 6:02

1 Answer 1

0

OK, thx to smnbbrv I found a "ok" version (without "MyStringEnumType")

  • now I have a enum
  • and a array
export class ComplexityOptions
{
    public static get Values()
    {
        return Object.keys(ComplexityOptions.Option).map((key: any) => (ComplexityOptions.Option[key]));
    }
}

export module ComplexityOptions
{
    export enum Option
    {
        Limited = 'limited',
        Low = 'low',
        Medium = 'medium',
        High = 'high'
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.