2017-09-13 130 views
1

我通過下面的代碼使用打字稿延伸的Javascript基本陣列對象用於角應用程式:擴展陣列工作在角組件視圖中,但不是角組件類

文件:utilities.ts

// --- Extends Array object to include a getIndexBy method. --- 
interface Array<T> { 
    getIndexBy(name: string, value: T): number; 
} 

// --- Returns the index of an object based on the name and value passed into the method. 
Array.prototype.getIndexBy = function(name, value) { 
    for (let i = 0; i < this.length; i++) { 
     if (this[i][name] === value) { 
      return i; 
     } 
    } 
}; 

文件:app.component.ts

import { Component } from '@angular/core'; 
import 'utilities'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    title = 'app works!'; 
    items: Array<{ name: string, age: number }> = [{ 
     name: 'steve', 
     age: 20 
    }, { 
     name: 'bob', 
     age: 12 
    }, { 
     name: 'john', 
     age: 40 
    }]; 

    constructor() { 
     console.log(this.items.getIndexBy('age', 20)); 
     // ERROR - Argument of type '20' is not assignable to parameter of type '{ name: string; age: number; }' 
    } 
} 

文件:app.component.html

<h1> 
    {{title}} 
</h1> 
<hr> 
{{items.getIndexBy('age', 12)}} <!-- Works as expected --> 
{{items.getIndexBy('name', 'john')}} <!-- Works as expected --> 

爲什麼我可以在視圖中使用擴展數組方法,但不能在組件類中使用擴展數組方法?

回答

0

由於類型不匹配,您將收到打印錯誤。你這樣定義getIndexBy:

getIndexBy(name: string, value: T): number 

其中T是數組的類型。你的數組是Array < {name:string,age:number}>,所以傳遞20不符合{name:string,age:number}。究竟如何解決這個問題取決於你的意圖。你的意思是讓getIndexBy成爲一個通用的?

您僅在.ts文件中看到此錯誤,而不在.html文件中,因爲打字稿檢查不在.html文件中完成。

+0

我明白了。是的,我的意圖是讓getIndexBy方法接受第二個通用參數 – YOOOEE

0

使用以下更新公用程序文件更正了問題。

interface Array<T> { 
    getIndexBy<U>(name: string, value: U): number; 
}