I have the following code:
const KeyboardEventKeys = {
Escape: 'Escape',
Enter: 'Enter',
Tab: 'Tab'
};
type KeyboardEventKeys = keyof (typeof KeyboardEventKeys);
function doSomething(key: KeyboardEventKeys) {}
When I'm passing to a function the value of one of the object properties it yells at me:
doSomething(KeyboardEventKeys.Enter);
One solution is to cast as KeyboardEventKeys
, but it's a redundant solution. How can I do it without it?
I also don't want to add doSomething(key: KeyboardEventKeys | string)
because I will lose the type guard.
The solution to use an enum is a good one, and I would recommend you use it.
The reason you get an error is that typescript will not infer string literal types for const members. You can force the compiler to infer string literal types by using an extra function when you create the const
:
function createEnum<T extends { [P in keyof T]: P }>(o: T) {
return o
}
const KeyboardEventKeys = createEnum({ // typed as { Escape: "Escape"; Enter: "Enter"; Tab: "Tab"; }
Escape: 'Escape',
Enter: 'Enter',
Tab: 'Tab'
});
type KeyboardEventKeys = keyof (typeof KeyboardEventKeys);
function doSomething(key: KeyboardEventKeys) { }
doSomething("Enter")
doSomething("") //err
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With