2016-04-27 31 views
0

let result: Array<any> = a.Where(func);というエラーが表示されます。方法whereはエラーが発生していますが、Array<any>を返します。タイプ 'Array <any>'は 'any []'タイプに割り当てられません。プロパティ '[Symbol.iterator]'がタイプ '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

答えて

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

+0

「グローバル」ファイルは何か説明できますか?実際には、次のようにコードを書いています。 'export {}; グローバル宣言{ インターフェイス配列 { 最初に:{ ():T; (Func:(x:T)=>ブール値):T; }; (Func :(x:T)=>ブール値):配列; } } –

+0

グローバル対モジュール:https://basarat.gitbooks.io/typescript/content/docs/project/modules.html – basarat

+0

コピーして、「typescript play ground」にコピーしてください。また、同じエラーが発生しています。 [Typescript Play Ground](https://www.typescriptlang.org/play/) 当面は以下のようにキャスティングオブジェクトを使用しています。それは大丈夫ですか? 'let result:Array = <[]> a.where(func); ' –

関連する問題