打字稿-在函数的参数中添加一个参数

时间:2020-02-20 15:47:21

标签: typescript

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

除了要在最后添加一个参数之外,我想创建一种与上述类型相同的类型。假设d:number;

type SomeFuncAltered = (a:string, b:number, c:someCustomType, d:number) => number;

尽管我不想手动制作整个类型,但我很确定这里有一个Parameters<func>有用的技巧。

2 个答案:

答案 0 :(得分:2)

您可以对基本函数args使用其他类型:

type FuncBaseArgs = {
  a: string;
  b: number;
  c: boolean;
}

type SomeFunc = ({...obj }: FuncBaseArgs) => number;

type SomeFuncAltered = ({...obj }: FuncBaseArgs, d: number) => number;

答案 1 :(得分:2)

有可能,但非常复杂。可以在@jcalz-Push type to the end of the tuple with skipping optional的答案中找到更多信息。

在您的情况下,我们可以重用上面答案中的一些实用程序,确切的说它们将是ConsPush,并通过使用它们来确定最终的类型,您需要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>