Leverage `enum` values in Typescript for typed definitions

I want to implement the values of the following enum:

export enum GenderFormats {
    SHORT_LOWER = 'm/f', SHORT_UPPER = 'M/F', FULL = 'Male/Female'
};

as a type shown below:

export interface IGenderOptions {
    format: 'm/f' | 'M/F' | 'Male/Female'
};

using Type extraction/definition like this:

{{some type cast/logic}}<GenFormats>    // Outputs: 'm/f' | 'M/F' | 'Male/Female'

Revised Question:

This is my code snippet:

export enum EGenderFormats {
    SHORT_LOWER = 'm/f', SHORT_UPPER = 'M/F', FULL = 'Male/Female'
};

export interface IGenderFormats {
    SHORT_LOWER: 'm/f'; SHORT_UPPER: 'M/F'; FULL: 'Male/Female';
};

export interface IGenderOptions {
    format: IGenderFormats[keyof IGenderFormats]
};

const DEFAULTS: IGenderOptions = {
    format: EGenderFormats.FULL
};

How can I utilize either enum EGenderFormats or interface IGenderFormats instead of both?

Running Typescript 3.2.2

Thank you

Answer №1

If you want to define gender options, you can utilize the Enum type:

export enum GenderFormats {
  ABBREVIATED_LOWER = "m/f",
  ABBREVIATED_UPPER = "M/F",
  FULL = "Male/Female"
}

type SpecificGenderOptions = "m/f" | "M/F" | "Male/Female"

export interface GenderOptions {
  format: GenderFormats | SpecificGenderOptions;
}

const DEFAULT_SETTINGS: GenderOptions = {
  format: GenderFormats.FULL
};

const CUSTOM_SETTINGS: GenderOptions = {
  format: "M/F"
};

Answer №2

With the most recent version of TypeScript, it is now possible to simply assign values directly. I have successfully set up my easy-peasy store for various pages using enums in my app.

import { Action, action, createStore } from "easy-peasy";
import { createTypedHooks } from "easy-peasy";

interface IStoreModel {
  page: Pages;
  setPage: Action<IStoreModel, Pages>;
}

enum Pages {
  Home = "home",
  Admin = "admin",
}

const typedHooks = createTypedHooks<IStoreModel>();

const store = createStore<IStoreModel>({
  page: Pages.Admin,
  setPage: action((state, payload) => {
    state.page = payload;
  }),
});

export const useStoreActions = typedHooks.useStoreActions;
export const useStoreDispatch = typedHooks.useStoreDispatch;
export const useStoreState = typedHooks.useStoreState;

If you are looking for more information on this topic, check out the following link: https://blog.logrocket.com/typescript-string-enums-guide
Remember to use typeof properly ;)

Answer №3

This question has been around for a while, but none of the responses seem to fully address it. Perhaps you are seeking:

keyof typeof EGenderFormats

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a mapped union type be created in TypeScript?

Can the features of "mapped types" and "union types" be combined to generate an expression that accepts the specified interface as input: interface AwaActionTypes { CLICKLEFT: 'CL'; CLICKRIGHT: 'CR'; SCROLL: 'S'; ZOOM ...

Type hints for the "default" object in TypeScript

Let's illustrate this question with a couple of examples: interface MyInput { reqString: string, reqNumber: number, optString?: string } const defaultValues: Partial<MyInput> = { reqString: "hello", optString: "goo ...

Multiple invocations of ngrx effects occur following its return of the value

When the value is returned, ngrx effects are triggered multiple times. loadMovies$: Observable<Action> = createEffect(() => { return this.actions$.pipe( ofType(counterActions.CounterActionTypes.IncrementCounter), flatMap(() => { ...

"Enhance the existing control in an Angular 2 FormGroup by adding validators based on the

My form is built using the FormGroup method. I need to add validators to specific controls that have data after the user inputs information and clicks on the 'check' button. Here's what I attempted: this.fg.controls['someKey'].s ...

Extending a class with diverse types in Typescript: A guide

I have a class with multiple methods that deal with an entity referred to as "entity." class entity { entityName: string = ''; getList(): any[] { someAPI + this.entityName .... } getOne(): any{ } } Additionally, there are specifi ...

Encountering an Angular 13 ChunkLoadError during application deployment, despite the presence of the respective chunk

We encountered an issue with our application's upgrade from Angular 11 to 13. While running 'ng serve' on the local machine works fine, deploying it to our Azure app service causes the lazy loaded modules to fail loading. The specific error ...

Passing Angular/Electron service output to a variable results in it being undefined

I am encountering a problem with my service. When I run the code marked #1, it successfully displays data in the console. However, when I attempt to assign it to a variable, I receive an undefined value. Here is the code snippet: Service: executeShell(c ...

`Planning the layout of an Angular application with distinct sections`

I've been working on breaking down my Angular app into separate sections and I have a few queries about how to proceed: auth login (only public page in the entire system, after login users are directed to either the admin or user portal based on ...

Named functions in Typescript within functional components are the best practice for improving

How can I implement handleFoo using MyType['foo']? type MyType { foo: () => void } const Comp: React.FunctionComponent<{}> = () => { function handleFoo() {} return ... } I'm looking for a solution that doesn't inv ...

Do promises within an array begin execution only when they are passed to Promise.all()?

When an array of promises is built and then passed to the Promise.all method, does execution start immediately or only once Promise.all is called? Consider the following code snippet: let promises: Promise<string> [] = [this.methodCall(), this.meth ...

Exploring Angular Component Communication: Deciphering between @Input, @Output, and SharedService. How to Choose?

https://i.stack.imgur.com/9b3zf.pngScenario: When a node on the tree is clicked, the data contained in that node is displayed on the right. In my situation, the node represents a folder and the data consists of the devices within that folder. The node com ...

How to easily enable or disable y-axis in Chart.js and customize their visibility

My Situation: Once the canvas is generated, I want to have a blank canvas area with no curves and no y-axis - surprisingly, it's working as expected. Starting View: https://i.sstatic.net/TzaTd.png Desired Outcome: When I click on a label (like Da ...

What is the most efficient way to organize a JSON by a designated property in order to showcase it in an Angular data table?

Hello, I have a question. I need to organize the JSON data obtained from an API before displaying it in a datatable. My goal is to sort the data by a specific property just before passing it to the datatable for direct display. Below is the code I use to ...

Generating objects dynamically using Angular 2 framework

My goal is to dynamically create objects and add data using TypeScript. For instance: let data={ "date":"27-5-2017", "name":"John" }; This represents my initial object. Now, I aim to include additional data in it, such as subjects. "Subject1":" ...

There is a Typescript error stating that the argument of type 'NodeListOf<HTMLInputElement> | undefined' cannot be assigned to the parameter of type 'Iterable<HTMLInputElement> ...'

While working on my React/Typescript App, I encountered an issue when trying to access an array of inputs in an event listener using 'e.currentTarget'. To solve this, I utilized Array.from() to convert the NodeListOf into an array and ensured tha ...

Need to import Vue component TWICE

My question is simple: why do I need to import the components twice in the code below for it to function properly? In my current restricted environment, I am unable to utilize Webpack, .vue Single File Components, or npm. Despite these limitations, I mana ...

Transfer of double array in Emscripten - A seemingly arbitrary address has been obtained

I am facing a challenge in passing a double array to a WASM file that is generated through emscripten. I have created it as a .js output file with WASM=1, which also gives me a wasm file. Below is an excerpt from my C++ code: #include <iostream> usi ...

Guide on posting an object in Angular through HTTP Post

I am attempting to send an object named Pack to my API Rest server using my Angular service. Below is the function I have set up for this task: save_pack(Pack: any){ return new Promise((resolve, reject) =>{ this.http .post("http://loca ...

Encountering error code TS1003 while trying to access object properties using bracket notation in Typescript

How can object property be referenced using bracket notation in TypeScript? In traditional JavaScript, it can be done like this: getValue(object, key) { return object[key]; } By calling getValue({someKey: 1}, "someKey"), the function will return 1. H ...

How can we enforce that only a certain type of ReactElement is allowed to be passed as props to a Component in TypeScript?

eslint and vscode seem to have trouble detecting validation errors when passing incompatible ReactElement types. Despite searching through documentation and examples, I haven't been able to find a solution that works. // Footer.tsx export interface ...