Typescript - 向函数的参数添加一个参数

Joh*_*ith 15 typescript

type SomeFunc = (a:string, b:number, c:someCustomType) => number;
Run Code Online (Sandbox Code Playgroud)

我想创建一种与上面的类型类似的类型,只是最后添加了一个参数。比方说,d:number

type SomeFuncAltered = (a:string, b:number, c:someCustomType, d:number) => number;
Run Code Online (Sandbox Code Playgroud)

不过,我不想手动制作整个类型,我很确定Parameters<func>这里可以使用一个聪明的技巧。

Mel*_*rse 16

由于此处接受的答案似乎对我不起作用(使用 TS 4),因此我编写了自己的类型,在函数末尾添加任意数量的参数。

type AddParameters<
  TFunction extends (...args: any) => any,
  TParameters extends [...args: any]
> = (
  ...args: [...Parameters<TFunction>, ...TParameters]
) => ReturnType<TFunction>;
Run Code Online (Sandbox Code Playgroud)

用法:

type SomeFunc = (a: string, b: number, c: someCustomType) => number;
type SomeFuncAltered = AddParameters<SomeFunc, [d: number]>;
// SomeFuncAltered = (a:string, b:number, c:someCustomType, d:number) => number;
Run Code Online (Sandbox Code Playgroud)

注意:此解决方案还允许您添加命名参数。

  • 这太棒了,谢谢!如果有人出于某种原因不想创建泛型类型,则只需替换参数即可。例如,我正在扩展 Keycloak OAuth 获取包装器的获取 API: `type FetchSecure = ( ...args: [...[keycloak: KeycloakInstance], ...Parameters&lt;typeof fetch&gt;] ) =&gt; ReturnType &lt;typeof fetch&gt;;` 注意 Keycloak 参数自 init 以来必须首先出现?fetch 的参数是可选的:) (2认同)

Mac*_*ora 3

这是可能的,但相当复杂。更多信息可以在这个答案中找到 @jcalz - Push type to the end of the tuple withskipping option

在您的情况下,我们可以重用上面答案中的一些实用程序,确切地说Cons,并且Push通过使用它们来制作您需要的最终类型AddArgument。考虑:

type SomeFunc = (a: string, b: number, c: string) => number;

// some utility types for working with tuples
type Cons<H, T extends readonly any[]> =
    ((head: H, ...tail: T) => void) extends ((...cons: infer R) => void) ? R : never;

type Push<T extends readonly any[], V>
    = T extends any ? Cons<void, T> extends infer U ?
    { [K in keyof U]: K extends keyof T ? T[K] : V } : never : never;

// final type you need
type AddArgument<F, Arg> = 
F extends ((...args: infer PrevArgs) => infer R) 
? (...args: Push<PrevArgs, Arg>) => R : never

// function type with added boolean argument at the end
type NewFunction = AddArgument<SomeFunc, boolean>
Run Code Online (Sandbox Code Playgroud)