输入&#39;数组<any>&#39;不能分配给任何[]&#39;类型。财产&#39; [Symbol.iterator]&#39;在类型&#39;数组<任何>&#39;中缺失

时间:2016-04-27 00:21:52

标签: typescript ecmascript-6

我在let result: Array<any> = a.Where(func);行遇到错误。方法where返回Array<any>但我收到错误。

    export {};

    type Predicate<T> = (item: T) => boolean;

    interface KeyArrayPair<K, T> {
        Key: K;
        Value: Array<T>;
    }

    declare global {
        interface Array<T> {
            First: {
                (): T;
                (Func: Predicate<T>): T;
            };
            Where(Func: Predicate<T>): Array<T>;
        }
    }

    Array.prototype.Where = function (func: (x: any) => boolean): Array<any> {
        let result: Array<any> = [];
        let a: Array<any> = this;
        for (let i of a) {
            if (func(i)) {
                result.push(i);
            }
        }
        return result;
    };

    Array.prototype.First = function (func?: (x: any) => boolean): any {
        let a: Array<any> = this;
        if (a.length === 0) {
            throw 'Array does not contain elements';
        }
        if (!func) {
            return a[0];
        }
        let result: Array<any> = a.Where(func);
        if (result.length === 0) {
            throw 'Array does not contain elements';
        }
        return result[0];
    };

enter image description here

1 个答案:

答案 0 :(得分:0)

以下在新的foo.ts文件中工作正常:

interface Array<T> {
    first: {
        (): T;
        (Func: (x: T) => boolean): T;
    };
    where(Func: (x: T) => boolean): Array<T>;
}
Array.prototype.where = function(func: (x: any) => boolean): Array<any> {
    let result: Array<any> = [];
    let a: Array<any> = this;
    for (let i of a) {
        if (func(i)) {
            result.push(i);
        }
    }
    return result;
};

Array.prototype.first = function(func?: (x: any) => boolean): any {
    let a: Array<any> = this;
    if (a.length === 0) {
        throw 'Array does not contain elements';
    }
    if (!func) {
        return a[0];
    }
    let result: Array<any> = a.where(func);
    if (result.length === 0) {
        throw 'Array does not contain elements';
    }
    return result[0];
};

更多

也许你是在模块中这样做的。请在全球文件中执行:https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html