How to build a type from enum values in TypeScript?

moltar picture moltar · Mar 13, 2019 · Viewed 9.8k times · Source

Given the following:

enum FooKeys {
  FOO = 'foo',
  BAR = 'bar',
}

I'd like to make an interface like this one, but instead of defining keys by hand, build it out of enum's values.

interface Foo {
  foo: string
  bar: string
}

Is something like this possible with TypeScript?

Thanks!

Answer

jcalz picture jcalz · Mar 13, 2019

Yes, you can use enum values as keys. And you can use a mapped type like the standard library's Record<K, V> to prevent repetition:

enum FooKeys {
  FOO = 'foo',
  BAR = 'bar',
}

// probably all you need, but it's a type alias
type FooType = Record<FooKeys, string>;

// if you need an interface instead you can do this
interface FooInterface extends FooType {};

And you can verify that it works:

declare const foo: FooInterface;
foo.foo; // okay
foo[FooKeys.FOO]; // okay

foo.bar; // okay
foo[FooKeys.BAR]; // okay

foo.baz; // error

Does that work for you? Good luck!