Last active
November 2, 2021 10:50
-
-
Save zzpmaster/fb62f7f8ffbc105f417075088e3ab711 to your computer and use it in GitHub Desktop.
Use Enum as restricted key type in Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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