Skip to content

Instantly share code, notes, and snippets.

@vpalos

vpalos/enum-keys.ts

Last active Feb 25, 2020
Embed
What would you like to do?
How to use `enum` values as strictly typed object keys in TypeScript.
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
You can’t perform that action at this time.