Home > Back-end >  How to make two enums have the same keys?
How to make two enums have the same keys?

Time:01-18

I have these two enums:

enum foo {
   bar,
   baz
}

enum fiz {
   ...
}

How can I make sure, that fiz has the same keys as foo? I tried adding an interface, but no luck with assigning.

CodePudding user response:

You can use a map.

enum foo {
  bar,
  baz,
}

const fiz = new Map<foo, string>([
  [foo.bar, 'value1'],
  [foo.baz, 'value2'],
]);

OR you can do something like this

enum Foo {
    A = "ActivityCode.Foo.A",
    B = "ActivityCode.Foo.B",
    C = "ActivityCode.Foo.C",
}

enum Bar {
    A = "ActivityCode.Bar.A",
    B = "ActivityCode.Bar.B",
    C = "ActivityCode.Bar.C",
}

enum Baz {
    A = "ActivityCode.Baz.A",
    B = "ActivityCode.Baz.B",
    C = "ActivityCode.Baz.C",
}

const ActivityCode = {
    Foo,
    Bar,
    Baz,
};

console.log(ActivityCode.Foo.A);

reference

CodePudding user response:

Based on your comment, I think this is approach will work well for you:

TS Playground

const keys = ['foo', 'bar', 'baz'] as const;
type Key = typeof keys[number]; // "foo" | "bar" | "baz"

type ObjectWithSameKeys<ValueType> = Record<Key, ValueType>;

const labels: ObjectWithSameKeys<number> = {
  foo: 1,
  bar: 2,
  baz: 3,
};

const names: ObjectWithSameKeys<string> = {
  foo: 'one',
  bar: 'two',
  baz: 'three',
};
  •  Tags:  
  • Related