Aligning arguments within the function signature

Is it possible to specify in TypeScript that the method 'foo' always expects FooData, etc. for the following code snippet:

const search = (data: FooData|BarData|BazData, method:"foo"|"bar"|"baz") => {
  //Perform some common operations
  return myClass[method](data);
}

The methods in myClass have signatures like this:

foo(data: FooData) => {
  //Do something
}

Edit: Relevant information: Getting keys of a class in typescript

Answer №1

To ensure the function parameters in a class stay synced, you can utilize overloads or leverage conditional types to extract specific methods and parameter types. By using a generic type argument in the function, you can establish the relationship between the method and data parameter:

type AppleData = { apple: number }
type OrangeData = { orange: number }
type BananaData = { banana: number }

class MyClass {

    apple(data: AppleData) {
        //Do Something
    }
    orange(data: OrangeData) {
        //Do Something
    }

    banana(data: BananaData) {
        //Do Something
    }    
}
type KeyOfType<T, V> = {
    [P in keyof T] : T[P] extends V? P: never
}[keyof T]

type Data<T, K extends PropertyKey> = T extends Record<K, (data: infer D) => void> ? D : never;

const search = <K extends KeyOfType<MyClass, (a: any) => any>>(method: K, data: Data<MyClass, K>) => {
    //Perform common tasks
    let myClass = new MyClass();
    return myClass[method](data);
}

search("apple", { apple: 1 })
search("apple", { orange: 1}) // error

Play

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

Looking to determine if two elements exist within an array? Seeking a boolean result based on their presence

Consider the following array of objects: quesListArray = [ { QuestionTypeID : 1, QuestionTypeName : 'Rating' }, { QuestionTypeID : ...

Serving HTML from NodeJS instead of JSON

I have implemented two middleware functions import { NextFunction, Request, Response } from 'express'; const notFoundHandler = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Page Not Found - ${req.originalUr ...

Passing data between Angular 2 components

Below is the component I am working with: @Component({ selector: 'myselector', providers: [ ], directives: [ ChildComponent], pipes: [ ], template: '<myselector>This is {{testEmitter}}</myselector>' }) export cla ...

Protected class, yet not transferable

My output varies based on the type of input provided. I have a custom guard in place to protect the input, but I'm still having trouble assigning it to the declared output: type InputType<Sub extends SubType> = { a: Sub, b: string } type SubTyp ...

Using multiple where conditions in TypeORM

SELECT * FROM clients WHERE preferred_site = 'techonthenet.com' AND client_id > 6000; Is there a way to execute this in the typeorm query builder? ...

Issue with React hook forms and shadcn/ui element's forwardRef functionality

Greetings! I am currently in the process of creating a form using react-hook-form along with the help of shadcn combobox. In this setup, there are two essential files that play crucial roles. category-form.tsx combobox.tsx (This file is utilized within ...

Limit an object to only contain interface properties

Suppose we have the following object: o {a : 1, b : 2} and this interface defined as: interface MyInterface { a : number } We are now looking to create a new object that represents the "intersection" of o and the MyInterface: o2 : {a : 1} The mai ...

Is there a different way to retrieve the tag name of an element besides using

Currently, I am dealing with an outdated version (Chromium 25) of chromium. My goal is to utilize the tagName method in order to retrieve the name of the specific HTML tag being used. While I am aware that Element.tagName functions for versions 43 and ab ...

Using a component again with variations in the input data

I'm looking to reuse a card component to display different types of data, but the @Input() properties are for different objects (articles and events). Parent HTML: <card-component [headline]="Articles" [content]="art ...

React Routing: Unleashing the Power of Multi-Level Routing

In my quest to create a route with multiple levels (<Route path="/hello/world" element={<a>hello world</a>} />), I encountered a few issues. Here are the versions I am using: react: 18.1 react-router-dom: 6.3.0 Success with O ...

Preventing Multiple Login Attempts in Angular.js Using Typescript

Is there a way to maintain the user login attempts limit even after page refresh? login() { /* Check if user has fewer than 5 failed login attempts */ if (this.failedAttempts < 4) { this.auth.login(this.credentials).subscribe(() => { this.rou ...

Cannot find property '' within type 'never'. (Using TypeScript useState with mapped JSON data from a server)

Currently, I am following a tutorial on using React with Material-UI and decided to add TypeScript into the mix. If you're interested, here is the link: Net ninja MUI The file Notes.tsx contains the code for fetching data from a JSON server and then ...

The downloaded zip file appears to be corrupt and cannot be opened

As a newcomer to TypeScript, I embarked on creating a simple function to download a zip file. This is the code I've managed to put together: import fs from 'fs'; import https from 'https'; export function handler(): void { https ...

What is the process for changing the text in a text box when the tab key on the keyboard is pressed in

When a user types a name in this text box, it should be converted to a specific pattern. For example, if the user types Text@1, I want to print $[Text@1] instead of Text@1$[Text@1]. I have tried using the keyboard tab button with e.keyCode===9 and [\t ...

Is it necessary to conceal Angular navigation controls when the user is not authenticated?

In Angular, is there a standardized method for hiding controls when the user is not logged in? We already have the CanActivate guard which checks if a user can access a route. Would it be better to hide the route initially if the user is not logged in or l ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

Using Angular's setTimeout() function with an external lambda that includes a parameter

My goal is to tackle two issues at once: 1) using setTimeout( #action#, timeMillis) with #action# as a lambda 2) supplying the lambda with a parameter. The common method of setTimeout( ()=>{ #callback# }, timeMillis) works flawlessly when extracting () ...

A guide on retrieving TypeScript mongoose/typegoose schema

Here is a defined schema for an account class AccountSchema; Below is the model declaration for the account const AccountClass: Model<AccountSchema & Document>; class Account extends AccountClass; Why isn't this functioning as expected? ...

Is there a TypeScript rule called "no-function-constructor-with-string-args" that needs an example?

The description provided at this link is concise: Avoid using the Function constructor with a string argument to define the function body This might also apply to the rule missing-optional-annotation: A parameter that comes after one or more optiona ...

Is it possible to retrieve and utilize multiple Enum values in Typescript?

Combine enum values to retrieve corresponding enum strings. Consider the following scenario: enum EnumDays { NONE = 0, SUN = 1, MON = 2, TUE = 4, WED = 8, THU = 16, FRI = 32, SAT = 64, ALL = 127 } If I pass a value o ...