【问题标题】:How to manually curry a function in TypeScript?如何在 TypeScript 中手动 curry 函数?
【发布时间】:2018-06-17 04:52:50
【问题描述】:

我遇到了一个提供外部 ts 类型的 js 库。假设是

interface ComplicatedFunction {
    (n: number, p: any): string,
    (s: string, p: any): number,
    (b: boolean, p: any): number,
}

declare const fn: ComplicatedFunction

我想咖喱它:

import fn from 'fn'
const curriedFn = (p1: ?) =>
    (p2: any) =>
        fn(p1, p2)

问题是p1的type是怎么填的? (所有严格检查)

我尝试使用泛型来修复类型:

const curry2 = <P1, P2, R>(fn: (n: P1, m: P2) => R) =>
    (n: P1) => (m: P2) => fn(n, m)

const curriedFn = curry2(fn)

不幸的是,curriedFn 属于签名(b: boolean, p: any): number。这样就省略了其他两个函数签名。

【问题讨论】:

    标签: typescript types functional-programming currying


    【解决方案1】:

    由于函数有一些决定结果类型的参数,你需要为柯里化函数使用类似的类型。不幸的是,类型推断在这里对你没有帮助,你需要手动指定类型,并在调用原始函数时使用一些额外的类型断言:

    const curriedFn : {
        (n: number): (p: any) => string,
        (s: string): (p: any) => number,
        (b: boolean): (p: any) => number,
    } = (p1: number | string | boolean) => (p2: any) => <any>fn(<any>p1, p2)
    

    【讨论】:

    • 其实lib是styled-components。我想咖喱styled函数。使用您的解决方案,我必须导出 ThemedBaseStyledInterface 中使用的大量接口。
    • 我刚刚尝试了那个特定的函数,它包含一个未导出的类型 (WithOptionalTheme),因此这样重新导出变得更加困难。但如果不是这样,该解决方案将起作用,您无需重新导出所有其他类型。
    • 对于这种特殊情况,我不确定您到底想要完成什么,但您必须使用的方法应该是相似的
    • 具体目标用法为:'const styleWith = (template: TemplateStringsArray, ...args: any[]) => (Comp: ?) => styled(Comp)(template, .. .args)'
    猜你喜欢
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2015-06-19
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多