使用
我有一个函数(下面称为runLater(,它接受两个参数:
- 任意函数
- 一组参数任意函数
像这样:
function runLater(aFunction, aFunctionsParams) {
// store for later use
}
如何键入runLater函数,以便当我将函数作为第一个参数传入时,第二个参数仅限于该函数的参数类型?
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
使用Parameters<T>
实用程序类型轻松实现
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'])