I'm striving to achieve the most precise solution for this issue. I have a parameter that can be a number or a valid string, and I am utilizing it as an index to retrieve the value of a declared enum.
Due to Typescript's lack of knowledge about the string's value, it throws: Element implicitly has an 'any' type because the index expression is not of type 'number'.ts(7015)
I find the use of any in cases like validWithArg2 to be messy and error-prone.
Is there a more elegant solution to this problem?
The snippet of code I referenced:
const f = (numOrString: number | string, strParam: string, numParam: number) => {
enum Enum {
'ATV' = 1,
'OLV' = 2,
'DC' = 3,
}
const validNum = Enum[0];
const validStr = Enum['ATV'];
const invalidArg = Enum[numOrString];
const invalidArg2 = Enum[strParam];
const validArg = Enum[numParam];
const validArg3 = Enum[numParam as any];
return {
invalidArg,
invalidArg3,
validArg,
validArg2,
validNum,
validStr,
};
};