简体   繁体   中英

How to type function that will infer params with Typescript?

I have a function called invoke which currently is typed like this:

export type InvokeType = <T = InvokeResponseTypes, Params = any>(
  methodName: InvokeMethodNameTypes,
  args?: Params
) => Promise<T>;

// for context, Invoke is a signalR method to call methods on a SignalR server.

InvokeMethodNameTypes are simply strings that call methods, like "GetUser" or "GetEvent" etc.

Each InvokeMethodNameType has corresponding args (Params) or none at all and I would use it like so:

const data = await invoke<GetEventResponseType, GetEventArgs>("GetEvent", { eventId })

This works but I do not feel like it is the correct approach to what I actually want to achieve.

Is it possible to type the invoke function so when passing a string such as "GetEvent" the arguments are automatically inferred to the correct object type?

Based on the code in the sandbox:

function myFunction(stringArg: 'person'): { name: string, age: number }
function myFunction(stringArg: 'car'): { make: string, model: string }
function myFunction(stringArg: any): any
{
  if (stringArg === "person") {
    return {
      name: "John",
      age: 20
    };
  }

  if (stringArg === "car") {
    return {
      make: "Mazda",
      model: "6"
    };
  }
}

let personResult = myFunction("person");
let personName = personResult.name;     // Okay
let personAge = personResult.age;       // Okay
let personMake = personResult.make;     // Error
let personModel = personResult.model;   // Error

let carResult = myFunction("car");
let carName = carResult.name;       // Error
let carAge = carResult.age;         // Error
let carMake = carResult.make;       // Okay
let carModel = carResult.model;     // Okay

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM