简体   繁体   English

Typescript如何删除函数类型的最后一个参数?

[英]Typescript how to remove the last parameter of a function type?

Assume I have a function type like this:假设我有这样的函数类型:

type Fn = (a: number, b: string, c: boolean) => void

And I want to create a new type with the last parameter removed, how can I do that?我想创建一个删除最后一个参数的新类型,我该怎么做?

type NewFn = RemoveLastParameter<Fn>

Expected type for NewFn : NewFn的预期类型:

type NewFn = (a: number, b: string) => void

I think you want something like:我想你想要这样的东西:

type Pop<T extends any[]> = T extends [...infer U, any] ? U : never

type RemoveLastParameter<T extends (...args: any[]) => any> =
    (...args: Pop<Parameters<T>>) => ReturnType<T>

Here Pop is a type that gets all members except the last of a tuple as U and then returns U .这里Pop是一种类型,它将除元组的最后一个成员之外的所有成员都作为U ,然后返回U

Then RemoveLastParameter simply accepts any function type and constructs a new function type with the function Parameters Pop ped.然后RemoveLastParameter简单地接受任何函数类型并使用函数Parameters Pop ped 构造一个新的函数类型。

Proof:证明:

type Fn = (a: number, b: string, c: boolean) => void
type NewFn = RemoveLastParameter<Fn>
// (a: number, b: string) => void


declare const newFn: NewFn
newFn(1, 'abc') // works

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM