【问题标题】:How to specify a type that represents the arg types of a specific function?如何指定表示特定函数的 arg 类型的类型?
【发布时间】:2022-01-16 06:36:02
【问题描述】:

我有一个接受两个参数的函数(下面称为 runLater):

  1. 任意函数
  2. 的参数数组 任意函数

像这样:

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

【问题讨论】:

  • 不传递函数和参数,而是使用闭包传递具有指定参数的函数。 runLater(() => logNameAndAge,('hoff', 42))
  • typescript 有一个名为 Parameters 的实用程序类型

标签: typescript typescript-generics


【解决方案1】:

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'])

【讨论】:

  • 太好了,谢谢@Inigo!
  • @Hoff 没问题!你见过六指的男人吗?
猜你喜欢
  • 2016-10-16
  • 1970-01-01
  • 2016-08-10
  • 2013-07-28
  • 2016-09-10
  • 2017-04-04
  • 2016-10-20
相关资源
最近更新 更多