Implementing TypeScript 2.8.4 in strict mode
Here's an enum example:
export enum TabIndex {
Editor = 'editor',
Console = 'console',
Settings = 'settings',
Outputs = 'outputs'
}
I am creating a Map from this enum:
tabs = new Map(<[string, string][]>Object.keys(TabIndex).map((key: any) => [TabIndex[key], key]));
Later on, I am trying to access a specific member from the Map using a query parameter:
const tabParam = this.urlSerializer.parse(this.location.path()).queryParams.tab; // can be 'editor', 'console', 'settings', etc.
Then I check if the Map has that particular key:
if (this.tabs.has(tabParam)) {
this.selectTab(TabIndex[this.tabs.get(tabParam)!]);
}
Despite this, TypeScript continues to throw an error:
Element implicitly has an 'any' type because index expression is not of type 'number'.
Although I am aware that the index type is a string, I want to stick with it due to enums supporting string values. Any suggestions on how to resolve this TypeScript error?
After some investigation, I came across a workaround mentioned in this comment utilizing keyof typeof
:
const tabParam: keyof typeof TabIndex = this.urlSerializer.parse(this.location.path()).queryParams.tab;
However, using this approach results in another TypeScript error:
Type 'string' is not assignable to type '"Editor" | "Console" | "Settings" | "Outputs"'