If you have string enum like so:
export enum LookingForEnum {
Romantic = 'Romantic relationship',
Casual = 'Casual relationship',
Friends = 'Friends',
Fun = 'Fun things to do!'
}
Then
const index: number = Object.keys(LookingForEnum).indexOf('Casual'); // 1
Answer from Sampath on Stack OverflowIf you have string enum like so:
export enum LookingForEnum {
Romantic = 'Romantic relationship',
Casual = 'Casual relationship',
Friends = 'Friends',
Fun = 'Fun things to do!'
}
Then
const index: number = Object.keys(LookingForEnum).indexOf('Casual'); // 1
When you declare that something is of type NubDirection then it's actually a number:
var a = NubDirection.INWARD;
console.log(a === 1); // true
When you access the enum using the ordinal you get back a string and not a number and because of that you can not assign it to something that was declared as NubDirection.
You can do:
nub.direction = NubDirection[NubDirection[index]];
The reason for this is that there's no such thing as enum in javascript, and the way typescript imitates enums is by doing this when compiling it to js:
var NubDirection;
(function (NubDirection) {
NubDirection[NubDirection["OUTWARD"] = 0] = "OUTWARD";
NubDirection[NubDirection["INWARD"] = 1] = "INWARD";
})(NubDirection || (NubDirection = {}));
So you end up with this object:
NubDirection[0] = "OUTWARD";
NubDirection[1] = "INWARD";
NubDirection["OUTWARD"] = 0;
NubDirection["INWARD"] = 1;
String enum can't be used to index into an object
How do I convert a string to enum in TypeScript? - Stack Overflow
dictionary - How to use enum as index key type in typescript? - Stack Overflow
Enum index signature to get enum value by string representation
Enums in TypeScript 0.9 are string+number based. You should not need type assertion for simple conversions:
enum Color{
Red, Green
}
// To String
var green: string = Color[Color.Green];
// To Enum / number
var color : Color = Color[green];
Try it online
I have documentation about this and other Enum patterns in my OSS book : https://basarat.gitbook.io/typescript/type-system/enums
Make sure to use this if you are using the typescript flag --noImplicitAny:
var color : Color = Color[green as keyof typeof Color];
As of Typescript 2.1 string keys in enums are strongly typed. keyof typeof is used to get info about available string keys (1):
enum Color{
Red, Green
}
let typedColor: Color = Color.Green;
let typedColorString: keyof typeof Color = "Green";
// Error "Black is not assignable ..." (indexing using Color["Black"] will return undefined runtime)
typedColorString = "Black";
// Error "Type 'string' is not assignable ..." (indexing works runtime)
let letColorString = "Red";
typedColorString = letColorString;
// Works fine
typedColorString = "Red";
// Works fine
const constColorString = "Red";
typedColorString = constColorString
// Works fine (thanks @SergeyT)
let letColorString = "Red";
typedColorString = letColorString as keyof typeof Color;
typedColor = Color[typedColorString];
https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types
|undefineddoes not make a property optional, just means it can beundefined, there is a proposal to make|undefinedmembers optional but currently it's not implemented. You need to use?after]to make all properties optional{ [key in DialogType]?: Dialog }You can use the dialog enum values as keys, but they need to be computed properties:
let openDialogs: { [key in DialogType]?: Dialog } = { [DialogType.Options]: undefined, };{ [key: number or string]: Dialog }is an index signature. Index signatures are restricted to onlynumberorstringas the key type (not even a union of the two will work). So if you use an index signature you can index by anynumberorstring(we can't restrict to onlyDialogTypekeys). The concept you are using here is called mapped types. Mapped types basically generate a new type based on a union of keys (in this case the members of DialogType enum) and a set of mapping rules. The type we created above is basically equivalent to:let o: { [DialogType.Help]?: Dialog; [DialogType.Options]?: Dialog; }
Here is an example of how to use enum as index in typescript:
enum DialogType {
Options,
Help,
About
}
type Dialog = {
whatever: string;
};
type DialogMap = { [key in DialogType]?: Dialog };
let o: DialogMap = {
[ DialogType.Options ]: { whatever: "1" },
[ DialogType.Help ]: { whatever: "2" }
};
I just came across this post https://github.com/microsoft/TypeScript/issues/37448...
Does anyone have the problem here? Are there any strategies you'd found to overcome it?
See Playground.
enum Environment {
Sandbox = "SANDBOX",
Production = "PRODUCTION",
}
const keys = Object.keys(Environment);
console.log(keys) // ["Sandbox", "Production"]
console.log(Environment.Sandbox) // SANDBOX
console.log(keys.indexOf(Environment.Sandbox)) -1
You would need Object.values(Environment).
You need to use Object.values instead of Object.keys. Since "SANDBOX" is the value.
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import "./App.css";
export enum Environment {
Sandbox = "SANDBOX",
Production = "PRODUCTION",
}
function App() {
const [selectedEnvironment, setSelectedEnvironment] = useState<Environment>(
Environment.Production
);
const val = Object.values(Environment).indexOf(selectedEnvironment);
return (
<div className="App">
<p>{selectedEnvironment}</p>
<p>{val}</p>
</div>
);
}
export default App;
Link
As described in the handbook:
Keep in mind that string enum members do not get a reverse mapping generated at all.
That means there is no simple reverse mapping in your case.
You can try some custom functions, like this:
function getEnumKeyByEnumValue(myEnum, enumValue) { let keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue); return keys.length > 0 ? keys[0] : null; }
You can use Object.entries(Locales) for obtain a two dimensional array which in the deep layer have [Country, string]. This is an example:
[ ['English', 'en'], ['China', '0']['Nigeria', '1'], ['Kenya', '2'] ]
If you want to obtain Kenya you can filter this array for search this value like this:
Object.entries(Locales).find(local=>local[1]==='2')[0]
This returns Kenya