【问题标题】:Typescript remove first argument from a function打字稿从函数中删除第一个参数
【发布时间】:2019-11-08 10:33:05
【问题描述】:

我有一个可能很奇怪的情况,我正在尝试用 typescript 建模。

我有一堆函数,格式如下

type State = { something: any }


type InitialFn = (state: State, ...args: string[]) => void

我希望能够创建一个表示InitialFn 的类型,并删除第一个参数。类似的东西

// this doesn't work, as F is unused, and args doesn't correspond to the previous arguments
type PostTransformationFn<F extends InitialFn> = (...args: string[]) => void

这可能吗?

【问题讨论】:

  • 我不太懂typescript,但是去掉第一个参数的initialFn,不完全是另一个函数吗?
  • 在普通 js 中,如果你想消除提供前导参数的需要,你可以使用 bind() 设置参数以在调用返回的函数时传递,即 a=(b,c)=&gt;{}; d=a.bind(null,6); 这样调用 d(7) , b 将永远是 6c 将是任何第一个传递给 d 的 arg 在这种情况下是 7。不确定 ts 语法是什么

标签: javascript typescript generics


【解决方案1】:

我认为你可以用更通用的方式做到这一点:

type OmitFirstArg<F> = F extends (x: any, ...args: infer P) => infer R ? (...args: P) => R : never;

然后:

type PostTransformationFn<F extends InitialFn> = OmitFirstArg<F>;

PG

【讨论】:

    【解决方案2】:

    您可以使用条件类型来提取其余参数:

    type State = { something: any }
    
    type InitialFn = (state: State, ...args: string[]) => void
    
    // this doesn't work, as F is unused, and args doesn't correspond to the previous arguments
    type PostTransformationFn<F extends InitialFn> = F extends (state: State, ...args: infer P) => void ? (...args: P) => void : never
    
    type X = PostTransformationFn<(state: State, someArg: string) => void> // (someArg: string) => void
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 2022-01-18
      相关资源
      最近更新 更多