Karl Taylor
Karl Taylor

Reputation: 5279

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?

Upvotes: 0

Views: 57

Answers (1)

md2perpe
md2perpe

Reputation: 3061

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

Upvotes: 1

Related Questions