TypeScript 2.8.4 in strict mode
I've got an enum like this:
export enum TabIndex {
Editor = 'editor',
Console = 'console',
Settings = 'settings',
Outputs = 'outputs'
}
Out of which I'm creating a Map like this:
tabs = new Map(<[string, string][]>Object.keys(TabIndex).map((key: any) => [TabIndex[key], key]));
Later on, I'm trying to get a particular member out of that Map using a query parameter which should be available in the Map:
const tabParam = this.urlSerializer.parse(this.location.path()).queryParams.tab; // this thign is either 'editor', 'console', 'settings', ... etc.
And then I do
if (this.tabs.has(tabParam)) { // at this point we know the tab is available
this.selectTab(TabIndex[this.tabs.get(tabParam)!]); // here, TS thinks the index may be undefined, that's why I'm using the non-null assertion operator "!"
}
This code still makes TS unhappy. It errors out with:
Element implicitly has an 'any' type because index expression is not of type 'number'.
And it is true, the index type is a string. But I know that and that's how it's supposed to be because enums support string values. Anybody an idea how to make TS happy here?
I did some research and this issue comment suggests this workaround using keyof typeof:
const tabParam: keyof typeof TabIndex = this.urlSerializer.parse(this.location.path()).queryParams.tab;
This just makes TypeScript unhappy again:
Type 'string' is not assignable to type '"Editor" | "Console" | "Settings" | "Outputs"'