Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript type string is not assignable to type keyof

Tags:

typescript

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.

like image 606
undefined Avatar asked Jan 23 '19 09:01

undefined


1 Answers

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
like image 189
Titian Cernicova-Dragomir Avatar answered Oct 16 '22 04:10

Titian Cernicova-Dragomir