javascript - 在 TypeScript 中将任意函数参数推断为对象或元组类型

标签 javascript function typescript arguments type-inference

我正在寻找类似这种类型的东西:

type ArgsType<F extends Function> = ...

哪里

ArgsType<(n: number, s: string)=>void>

会给我

[number, string]

{n: number, s: string}

根据其中一个答案,我创建了以下类型:

type ArgsType<F extends (...x: any[]) => any>
    = F extends (...x: infer A) => any ? A : never;

type CtorArgsType<F extends new (...x: any[]) => any>
    = F extends new (...x: infer A) => any ? A : never;


interface RepoGroup {
    resetAsync?: () => Promise<void>
}

interface RepoGroupOptions<Reset extends "CanReset" | "CannotReset"="CannotReset"> {
    reset: Reset extends "CanReset" ? () => Promise<void> : undefined
}

type RepoGroupCtor<Reset extends "CanReset" | "CannotReset"="CannotReset">
    = new (...args: any[]) => RepoGroupOptions<Reset>


export function generate<
    CanReset extends "CanReset" | "CannotReset"="CannotReset",
    T extends RepoGroupCtor<CanReset>=RepoGroupCtor<CanReset>
    >(args: T) {
    return class implements RepoGroup {
        private args: InstanceType<T>
        constructor(...config: CtorArgsType<T>) {
            this.args = new args(config) as any
        }

        resetAsync = this.args.reset
    }
}


export const Repo = generate(class {
    readonly baseUrl: string
    constructor(args: { apiBaseUrl: string }) {
        this.baseUrl = args.apiBaseUrl
    }

    reset: undefined
})

let repository = new Repo()

最后一行显示了一个错误,这是应该的。但是,如果我只向存储库添加一个通用参数,则:

export const Repo = generate<"CannotReset">(class {...

然后错误就消失了,这看起来像是一个错误

最佳答案

type Parameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never;

这是 proposed to be added to the standard library .

第二轮

当您将至少一个类型参数传递给 generate 时,您关闭剩余类型参数的推理并使用默认值( T = RepoGroupCtor<CanReset> )和 RepoGroupCtor<CanReset>接受剩余参数 any[] ,因此没有错误。 Partial type argument inference将为您提供避免这种情况的方法。

关于javascript - 在 TypeScript 中将任意函数参数推断为对象或元组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52101351/

相关文章:

oop - 在 TypeScript 中扩展 React 组件

javascript - ignore 参数在 gulp 和 nodemon 中如何工作?

javascript 使用过滤器 w && 不返回所需的 console.log

javascript - 如何在 jquery 中对未命名函数调用 .call()?

javascript - "DataTable is not a function"$-issue/-conflict(jQuery 和新主题)

TypeScript 和迭代器 : Type 'IterableIterator<T>' is not an array type

class - 编写 TypeScript 装饰器以始终将类方法绑定(bind)到 'this'

javascript - 我无法执行需要使用 axios 设置 header 的请求

javascript - Google Ajax 语言翻译问题

javascript - 在 Javascript 中返回图像的数据 URI Base64 字符串的函数