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'.
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.
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.
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.
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
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