【问题标题】:How to re-use arguments signature for a function in TypeScript?如何在 TypeScript 中为函数重用参数签名?
【发布时间】:2020-05-21 21:34:44
【问题描述】:

我有一个函数的类型签名

type ExecCallbackType = (code: number, stdout: string, stderr: string, cmdType: CmdType) => void

我需要为许多函数创建一个类型签名,其中始终传递这 3 个参数、代码、标准输出和标准错误

这里是我的“可重复使用”类型:

export type ExecCallback = (
    code: number,
    stdout: string,
    stderr: string
) => any;

如何创建一个可以包含在 ExecCallback + cmdType:string 上的新类型签名

我尝试过的没有成功:

type ExecCallbackType = (ExecCallback & cmdType: CmdType) => void

有什么想法吗?谢谢

【问题讨论】:

标签: typescript


【解决方案1】:

也许这就是你要找的 -

type CmdType = {}

type ExecCallback = (
    code: number,
    stdout: string,
    stderr: string
) => any

type Param = Parameters<ExecCallback>

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;

type FullParams = Push<Param, CmdType>
type ExecCallbackType = (...args: FullParams) => void

Playground

另外,请参阅 this 帖子以获取 ConsPush

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多