打字稿:错误的返回类型

时间:2019-12-13 09:47:36

标签: typescript rxjs

我创建了一个函数,该函数接受某些类型的值并对其进行过滤。在这里:

import {isMatch} from 'lodash';

export function predicate<T>(compareWith: Partial<T>): OperatorFunction<T[], T[]> {
    return src$ => src$.pipe(map(value => {
        if (Array.isArray(value)) {
            return value.filter(element => isMatch(element as any, compareWith));
        }
        throw new Error('Value is not an array');
    }));
}

现在,当我在Customer类型模型(如predicate({CustomerId: 100})CustomerIdCustomer模型的属性)的数组上使用它时,出现以下错误:

Type 'Observable<{ CustomerId: Number; }[]>' is not assignable to type 'Observable<Customer[]>'.

但是,如果我明确地将其称为predicate<Customer>({CustomerId: 100}),它将可以正常工作。

如何正确配置类型以将客户作为返回类型?

这是一个失败的函数:

getCustomers(customerId) {
   return method$<Customer[]>.pipe(predicate({CustomerId: customerid}));
}

更新:

这是一个小解决方法,可以解决。但我不喜欢它:

export function predicate<T, P extends T>(compareWith: Partial<P>): OperatorFunction<T[]> {
    return src$ => src$.pipe(map(value => {
        if (Array.isArray(value)) {
            return value.filter(element => isMatch(element as any, compareWith));
        }
        throw new Error('Value is not an array');
    }));
}

0 个答案:

没有答案