Iは、次のコードを介して活字体を使用して角度のアプリ用の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.html
: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.ts
ビューでは拡張配列メソッドを使用できますが、コンポーネントクラスでは使用できません。
です。はい、私の意図は、getIndexByメソッドに第2の汎用パラメータを受け入れることでした – YOOOEE