Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access Typescript Enum by ordinal

Tags:

typescript

I have the following...

enum NubDirection {   OUTWARD,   INWARD } ... direction : NubDirection; ... let index = Math.floor(Math.random() * 2) + 1; nub.direction = NubDirection[index]; 

But this throws

error TS2322: Type 'string' is not assignable to type 'NubDirection'.

like image 625
Jackie Avatar asked Sep 10 '16 15:09

Jackie


People also ask

How do I index an enum in TypeScript?

Use the Object. values() method to get an array containing the enum's values. Use square brackets to access the array at the specific index and get the value.

How does TypeScript enum work?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Can I use TypeScript enum in JavaScript?

Enums are a feature added to JavaScript in TypeScript which makes it easier to handle named sets of constants. By default an enum is number based, starting at zero, and each option is assigned an increment by one. This is useful when the value is not important.


1 Answers

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 
like image 155
Sampath Avatar answered Oct 02 '22 18:10

Sampath