【问题标题】:TypeScript: how to get the types of the parameters of a callable? [duplicate]TypeScript:如何获取可调用参数的类型? [复制]
【发布时间】:2018-03-24 15:13:46
【问题描述】:

TypeScript 有 typeofkeyof。我正在寻找可以让我将可调用的参数类型作为元组的东西。例如,

import subject, { ParamA, ParamB, Output } from '.'
interface TestCase {
  input: (typeof subject).parameters // or perhaps `parametersof subject`
  key: keyof Output
  expectedValue: string
}

我知道我可以做到input: [ParamA, ParamB] 并完成它,但是......你知道......

【问题讨论】:

    标签: typescript


    【解决方案1】:

    不干净,不。 TypeScript 当前(从 2.5 版开始)缺少 type operators 那种可以让你从函数类型中干净地提取参数类型的类型。有一个proposal 可以让你在任意表达式上使用typeof,这会给你一种方法来获得它。目前,您可以这样做(仅适用于两个参数,如果需要可以扩展为更多):

    const params = (false as true) &&
      (null! as <T, U>(f: (p1: T, p2: U, ...rest: any[]) => any) => [T, U])(subject);
    
    interface TestCase {
      input: typeof params
      key: keyof Output
      expectedValue: string
    }
    

    它欺骗类型系统提取subject 的参数类型并声明该类型的params 常量。在运行时,params 将只是 false,这很好,因为您实际上不能让函数在运行时返回其参数类型。

    它很丑(一个虚拟常量乱扔你的代码)但它可以工作。

    希望有所帮助;祝你好运!

    【讨论】:

    猜你喜欢
    • 2019-01-21
    • 2013-02-03
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多