i'm having a typescript shown below.
enum Categories {
textbox = 1,
password
}
let typedata:string ="textbox";
let enumdata:Categories;
I want to convert this textbox string to enum. So that I can assign it in enumdata variable. When i tried to do this using
enumdata=Categories[typedata]
i'm getting an error
Element implicitly has an 'any' type because the index expression is not of type 'number'
Please let me know if anyone faced this issue. Please provide me with example if you found a solution for this.
My typescript version is 2.6.2
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"dom",
"es2015"
],
"noImplicitAny": false,
"sourceMap": true,
"rootDir": "src",
"outDir": "dist",
"noEmitOnError": true
}
}
Thank you Vipin
The error "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type" occurs when we use a string to index an object with specific keys. To solve the error, type the string as one of the object's keys.
In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.
The error "Type string is not assignable to type Enum" occurs when we try to use a string literal in the place of an enum value. To solve the error, use dot or bracket notation to access the specific enum property or use a type assertion.
In typescript, enums are only indexable by number and the exact property name.
It expects the identifier textbox
or 0
with type of "textbox"
or number
, but receives that value as type of string.
To work around this you can declare a type that ensures the right property name is used to get the corresponding enum value. eg:
enum Categories {
textbox = 1,
password
}
declare type CategoryType = keyof typeof Categories;
const getCategory = (key: CategoryType) => Categories[key];
/* The following will work as well, but does not ensure the correct typecheck when calling the function.
However you can keep you 'typedata' field as type of string. */
// const getCategory = (key: string) => Categories[key as CategoryType];
let enumdata: Categories;
const typedata: CategoryType = "textbox";
enumdata = getCategory(typedata);
...or simply
const typedata: string = "textbox";
enumdata = Categories[typedata as CategoryType];
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