【问题标题】:Typescript Inference for Pipeable Function可管道函数的打字稿推理
【发布时间】:2021-06-30 19:12:03
【问题描述】:

我正在开发一个包装数组并创建可管道过滤函数的类。

但是,Typescript 推理不适用于谓词函数。我认为它与通用范围有关,有没有办法解决这个限制?

class SomeClass<T> {
    constructor(public arr: Array<T>) {}
}

function filter <R> (fn: (r: R) => boolean) {
    return function (obj: SomeClass<R>) : SomeClass<R> {
        return new SomeClass(obj.arr.filter(fn));
    }
} 

/* How to replace i: unknown with i: number? */
let r = filter (i => i > 2) (new SomeClass([1, 2, 3]))
console.log(r);

【问题讨论】:

    标签: typescript generics filter functional-programming pipe


    【解决方案1】:

    您需要将泛型类型传递给函数,还需要使用构造函数初始化一些属性,或者只需将SomeClass 更改为一些泛型T 的数组。

    像这样:

    class SomeClass<T> {
        constructor(public arr: Array<T>) {}
    }
    
    function filter <R> (fn: (r: R) => boolean) {
        return function (obj: SomeClass<R>) : SomeClass<R> {
            return new SomeClass(obj.arr.filter(fn));
        }
    } 
    
    /* How to replace i: unknown with i: number? */
    let r = filter<number>(i => i >= 2) (new SomeClass([1, 2, 3]))
    console.log(r);
    

    【讨论】:

      猜你喜欢
      • 2017-11-03
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多