【问题标题】:Extended Array works in Angular component view, but not Angular component class扩展数组适用于 Angular 组件视图,但不适用于 Angular 组件类
【发布时间】: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


    【解决方案1】:

    您收到打字稿错误,因为类型不匹配。您像这样定义 getIndexBy:

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

    其中 T 是数组的类型。您的数组是 Array,因此传递 20 与 {name: string, age: number} 不匹配。究竟如何解决这个问题取决于您的意图。您的意思是让 getIndexBy 成为泛型吗?

    您仅在 .ts 文件中看到此错误,而在 .html 文件中看不到,因为没有对 .html 文件进行打字稿检查。

    【讨论】:

    • 我明白了。是的,我的意图是让 getIndexBy 方法接受第二个泛型参数
    【解决方案2】:

    使用以下内容更新实用程序文件更正了该问题。

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

    【讨论】:

      猜你喜欢
      • 2017-02-26
      • 2020-04-19
      • 2022-01-21
      • 2020-05-31
      • 2017-07-13
      • 2017-06-11
      • 1970-01-01
      • 2021-09-08
      • 2017-09-01
      相关资源
      最近更新 更多