Sending enums as arguments to a function

Is there a way to create a function that can work with any enum and function that accepts it as an argument? Consider the following scenario:


enum Enum1 {
  VALUE1 = "value1"
}
enum Enum2 {
  VALUE2 = "value2"
}

const func1 = (e: Enum1) => e;

const func2 = (e: Enum2) => e.toUpperCase();

const genericFunc = (e: Enum1 | Enum2, func: (e: Enum1 | Enum2) => typeof e) => func(e);

console.log(genericFunc(Enum1.VALUE1, func1)); // error with func1
console.log(genericFunc(Enum2.VALUE2, func2)); // error with func2

Is there a way to make this approach more flexible without resorting to using any?

Answer №1

It's important to note that this method allows for ff to return either E1, E2, or string, enabling f2 to function properly.

const ff = <Type extends E1 | E2>(e: Type, f: (arg: Type) => Type | string) => f(e);

Update

The idea of using T extends enum as mentioned by the original poster would be ideal, but unfortunately, it is still a work in progress and is being discussed in the following issue on GitHub.

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

Utilizing Angular Pipes for Utilizing Location

The Location service in Angular is described as "A service that applications can use to interact with a browser's URL." One of its methods, getState(), provides "the current state of the location history," while another method, subscribe(), allows us ...

What is the best way to determine the number of queryClient instances that have been created?

Currently, I am managing a large project where the code utilizes useQueryClient in some sections to access the queryClient and in other sections, it uses new QueryClient(). This approach is necessary due to limitations such as being unable to invoke a Reac ...

An issue has occurred with attempting to access the 'phone' property of a null value. This error is at the root of the problem and needs to

I have implemented a function to retrieve all clients from an API: this.ws.getallclients().subscribe( client => { this.client = client.map((clients) => { this.filteredOptions = this.addsale.controls['client_id'].valueChanges. ...

Tips for including additional properties to a <button> element using ReactJS and Typescript

Currently, I am in the process of creating a unique component which consists of an ordinary <button> tag and has a new prop called aria-current. The issue at hand is that Typescript is flagging an error stating that this property does not exist with ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...

Creating an extended class in Typescript with a unique method that overrides another method with different argument types

I need to change the argument types of a method by overriding it: class Base { public myMethod(myString: string): undefined { return; } } class Child extends Base { public myMethod(myNumber: number): undefined { return super.m ...

Adjust the Angular menu-bar directly from the content-script of a Chrome Extension

The project I've been working on involves creating an extension specifically for Google Chrome to enhance my school's online learning platform. This website, which is not managed by the school itself, utilizes Angular for its front-end design. W ...

Exploring the Incorporation of String as a Component Identifier in React and TypeScript

My input component can render either a textarea component (from a library) or a regular input. Check out the code below: import React, { useEffect, useRef, useState } from 'react' import './AppInput.css' interface Props { placehold ...

Exploring the Integration of OverlayScrollbars with TypeScript

Currently, I am delving into TypeScript utilizing a project built on ASP.NET Core 3.0 and the VS 2019 IDE. Recently, I acquired the OverlayScrollbars plugin via npm: . npm install overlayscrollbars npm install @types/overlayscrollbar Provided below is a ...

Transforming a base64 string into a uint8Array or Blob within Typescript/Angular8

I'm new to handling Base64 encoded strings, uint8Array, and Blobs. I've integrated a pdf viewer library from this repository https://github.com/intbot/ng2-pdfjs-viewer into our Angular 8 web application. I'm facing an issue where I am sendin ...

Issue with Vue 3 / Typescript: Unable to locate variable name in template

When working with Vue 3 and Typescript, I encountered an error that says "Cannot find name" when trying to reference a data variable in a certain area. How can I resolve this issue? Attached is a screenshot for reference: https://i.sstatic.net/1fknF.jpg. ...

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...

How can React TypeScript bind an array to routes effectively?

In my project, I am using the standard VisualStudio 2017 ASP.NET Core 2.0 React Template. There is a class Home included in the template: import { RouteComponentProps } from 'react-router'; export class Home extends React.Component<Rout ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

Deciding the conditional type within an IDE while using an If statement

When dealing with a type that can have two formats based on the value of one of its keys, such as: type singleOrMultiValue = {isSingle: true, value: string} | {isSingle: false, set: Array<string>} I have found it useful in preventing errors like con ...

Create a custom component that wraps the Material-UI TextField component and includes default

I have been exploring React and had a question regarding wrapping a component like TextField from mui to add new props along with the existing ones. I attempted to do this but am struggling to figure out how to access the other props. Can anyone help me ...

Accurate function calls with multiple parameters in TypeScript

As a beginner in TypeScript and currently exploring its integration with AngularJS, I am facing a particular issue where the compiler is not detecting an error. In Angular, a resource provider typically includes a get() method that returns an instance of ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...

Unlocking 'this' Within a Promise

I seem to have an issue with the 'this' reference in the typescript function provided. It is not correctly resolving to the instance of EmailValidator as expected. How can I fix this so that it points to the correct instance of EmailVaildator, al ...

The FOR UPDATE clause is not functioning as intended in the SELECT query

I have been working on isolating my database to prevent multiple servers from reading or updating data in the same row. In order to achieve this, I have structured my query like so: SELECT * FROM bridge_transaction_state as bridge WHERE bridge.state IN (&a ...