打字稿:声明并实现一个curried方法

时间:2017-03-21 08:58:07

标签: typescript currying

在以下类的骨架中

class Iterable<A> {

    filter( filter: ( value: A ) => boolean ): Iterable<A> { ... }

    map<B>( f: ( value: A, index?: number ) => B ): Iterable<B> { ...}

    collect = <B>( filter: ( value: A ) => boolean ) => ( mapper: ( value: A ) => B ): Iterable<B> => { ... }

}

有一个curried属性collect以这种方式实现

collect = <B>( filter: ( value: A ) => boolean ) => ( mapper: ( value: A ) => B ): Iterable<B> => {
    return this.filter( filter ).map( mapper )
}

这个属性基本上是一个curried函数,它接受两个函数作为参数并返回Iterable<B>thisIterable<A>,可以按以下方式使用:

const it: Iterable<string> = this.collect<string>( f => true )( ( v: A ) => v.toString() )

现在,我想将此属性转换为类方法,但我找不到正确的语法

  • 声明

    collect<B>( filter: ( value: A ) => boolean ): ( mapper: ( value: A ) => B ) => Iterable<B>
    

    会保留其用法(请参阅上面的it),但我不知道如何实现它,因为该方法需要返回Function,而不是Iterable

  • 声明

    collect<B>( filter: ( value: A ) => boolean ) => ( mapper: ( value: A ) => B ) : Iterable<B>
    

    无效......

解决方案:(参见@JLRishe和@NitzanTomer答案)我去了一个明确的类型声明:

collect<B>(filter: (value: A) => boolean): (mapper: (value: A) => B) => Iterable<B> {
    return (mapper: (value: A) => B) => this.filter(filter).map(mapper);
}

2 个答案:

答案 0 :(得分:1)

您可以像这样实现:

collect<B>(filter: (value: A) => boolean) {
    return (mapper: (value: A) => B) => this.filter(filter).map(mapper);
}

答案 1 :(得分:1)

怎么样

collect<B>(filter: (value: A) => boolean) {
    return (mapper: (value: A) => B): Iterable<B> => {
        return this.filter(filter).map(mapper);
    };
}