Last active
February 25, 2020 06:46
-
-
Save vpalos/0aab903ef607d6da31229b957d91d888 to your computer and use it in GitHub Desktop.
How to use `enum` values as strictly typed object keys in TypeScript.
This file contains hidden or 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 DialogButton { | |
YES = "yes", | |
NO = "no", | |
CANCEL = "cancel" | |
} | |
interface IDialog { | |
buttons: { [B in DialogButton]?: boolean }, | |
callback: (button: DialogButton) => void | |
} | |
const dialog: IDialog = { | |
buttons: { | |
[DialogButton.YES]: true, | |
[DialogButton.NO]: false | |
}, | |
callback(button) { | |
console.log(button) | |
} | |
} | |
console.log(DialogButton.YES in dialog.buttons) // true | |
console.log(DialogButton.NO in dialog.buttons) // true | |
console.log(DialogButton.CANCEL in dialog.buttons) // false | |
console.log(dialog.buttons[DialogButton.YES]) // true | |
console.log(dialog.buttons[DialogButton.NO]) // false | |
console.log(dialog.buttons[DialogButton.CANCEL]) // undefined | |
dialog.callback(DialogButton.YES) // yes | |
dialog.callback(DialogButton.NO) // no | |
dialog.callback(DialogButton.CANCEL) // cancel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment