Home > OS >  How to specify a type that represents the arg types of a specific function?
How to specify a type that represents the arg types of a specific function?

Time:12-13

I have a function (called runLater below) that takes two parameters:

  1. an arbitrary function
  2. an array of parameters for that arbitrary function

like this:

function runLater(aFunction, aFunctionsParams) {
    // store for later use
}

How can I type the runLater function, so that when I pass in a function as first parameter, the second parameter is restricted to the parameter types of that function?

function logNameAndAge(name: string, age: number) {...}

runLater(logNameAndAge, ['hoff', 42]) // ok, the parameter types match up
runLater(logNameAndAge, [false, 'oops']) // no ok, someFunction has [string, number] as paramters

CodePudding user response:

easy peasy with Parameters<T> utility type!

type func = (...args: any) => any

function runLater<T extends func>(aFunction: T, aFunctionsParams: Parameters<T>) {
    // store for later use
}

function logNameAndAge(name: string, age: number) {}

// ok:
runLater(logNameAndAge, ['hoff', 42])

// errors:
//   Type 'boolean' is not assignable to type 'string'.(2322)
//   Type 'string' is not assignable to type 'number'.(2322)
runLater(logNameAndAge, [false, 'oops'])
  • Related