【发布时间】:2018-02-22 07:47:53
【问题描述】:
我正在通过以下代码使用 Typescript 为 Angular 应用程序扩展 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 -->
为什么我可以在视图中使用扩展数组方法,而在组件类中却不行?
【问题讨论】:
标签: angular typescript