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

crazyx13th
  • 533
  • 5
  • 10
  • Why don’t you use normal enum? – smnbbrv Sep 05 '18 at 17:24
  • Possible duplicate of (or related to) [TypeScript String Union to String Array](https://stackoverflow.com/questions/44480644/typescript-string-union-to-string-array) – jcalz Sep 05 '18 at 18:45
  • I'll call it a duplicate. Possible duplicate of [TypeScript String Union to String Array](https://stackoverflow.com/questions/44480644/typescript-string-union-to-string-array) – Matt McCutchen Sep 05 '18 at 18:56
  • The above code seems to be right, is there any issue or problem? – Reza Sep 05 '18 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! – crazyx13th Sep 06 '18 at 06:02
  • @jcalz, RezaRahmati: sorry, but **TypeScript String Union to String Array** is not the solution. I will edit my post for - I hope - better unterstanding, thx! – crazyx13th Sep 06 '18 at 06:30
  • `enum` objects are difficult to manipulate at the type level for [various reasons](https://github.com/Microsoft/TypeScript/issues/21998). You want to widen the `MyEnum` type to its string values (`Both` should really just be the string values, since `MyEnum extends MyStringEnumType`) but there's currently no programmatic way to do that in TypeScript. – jcalz Sep 06 '18 at 13:03

1 Answers1

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'
    }
}
crazyx13th
  • 533
  • 5
  • 10