TypeScript:编译器忽略替代函数签名

时间:2016-05-19 14:53:53

标签: typescript

我正在使用lodash和TypeScript 1.8。在代码中的某一点,我想从这样的数组中减少:

export interface IPackage {
    [...]
    dependencies?: IPackageReference[];
    [...]
}

[...]

// pkg implements IPackageReference
lodash.reduce<IPackageReference, boolean>(pkg.dependencies, function(ref: IPackageReference, state: boolean) {
  return true;
}, true);

但是,编译器退出时类型不匹配:

package.ts(43,39): error TS2345: Argument of type 'IPackageReference[]' is not assignable to parameter of type 'Dictionary<IPackageReference>'.
  Index signature is missing in type 'IPackageReference[]'.

我使用的输入法支持Arrays作为第一个参数:

    /**
    * @see _.reduce
    **/
    reduce<T, TResult>(
        collection: Array<T>,
        callback: MemoIterator<T, TResult>,
        thisArg?: any): TResult;

    /**
    * @see _.reduce
    **/
    reduce<T, TResult>(
        collection: List<T>,
        callback: MemoIterator<T, TResult>,
        thisArg?: any): TResult;

    /**
    * @see _.reduce
    **/
    reduce<T, TResult>(
        collection: Dictionary<T>,
        callback: MemoIterator<T, TResult>,
        thisArg?: any): TResult;

如何让TSC将我的参数识别为数组?

2 个答案:

答案 0 :(得分:1)

您的减速器功能参数已根据the documentation反转。尝试切换订单。

// pkg implements IPackageReference
lodash.reduce<IPackageReference, boolean>(pkg.dependencies, function(state: boolean, ref: IPackageReference) {
  return true;
}, true);

有时这样的事情会产生下游效应,其中对象碰巧可以解释为错误的类型,因此编译器会继续。

答案 1 :(得分:0)

我已经将reduce回调的参数转换出来,就像@Paarth提到的那样。但是,由于错误出现在第一个参数上,我有点误导。这是由于TypeScript如何处理多个函数签名。如果任何匹配失败,则对最后定义的签名进行错误检查,而不是最接近的匹配。

GH问题:https://github.com/Microsoft/TypeScript/issues/8693