Skip to content

Instantly share code, notes, and snippets.

@zzpmaster
Last active November 2, 2021 10:50
Show Gist options
  • Save zzpmaster/fb62f7f8ffbc105f417075088e3ab711 to your computer and use it in GitHub Desktop.
Save zzpmaster/fb62f7f8ffbc105f417075088e3ab711 to your computer and use it in GitHub Desktop.
Use Enum as restricted key type in Typescript
enum Foo {
A = 'a1', B = 'b1', C = 'c1'
}
// use enum value
const finish = (): Partial<{ -readonly [key in Foo]: string }> => {
return { [Foo.A]: 'hello'}; // or { 'a1': 'hello' }
}
// use enum key
const finish1 = (): Partial<{ -readonly [key in keyof typeof Foo]: string }> => {
return { A: 'hello'};
}
const result = finish();
result.a1 = 'other value'
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment