【问题标题】:TypeScript Generic Collection: ListTypeScript 通用集合:列表
【发布时间】:2018-01-01 01:09:25
【问题描述】:

我正在尝试学习 TypeScript,并且需要一些关于实现泛型集合类型的建议。我将字典和 HashSet 放在另一个问题中,在这里我想对我的列表类型提出任何建议。

尤其是 ForEach-Operation 看起来有点奇怪。我想我在这里的另一个问题中找到了它,并通过返回 true 或 false 来“改进”以在迭代提前停止或完成时提供反馈。

import { IForEachFunction } from "./IForEachFunction"

export class List<T> {
    private _items: Array<T>;

    public constructor() {
        this._items = [];
    }

    public get Count(): number {
        return this._items.length;
    }

    public Item(index: number): T {
        return this._items[index];
    }

    public Add(value: T): void {
        this._items.push(value);
    }

    public RemoveAt(index: number): void {
        this._items.splice(index, 1);
    }

    public Remove(value: T): void {
        let index = this._items.indexOf(value);
        this.RemoveAt(index);
    }

    public ForEach(callback: IForEachFunction<T>): boolean {
        for (const element of this._items) {
            if (callback(element) === false) {
                return false;
            }
        }

        return true;
    }
}

ForEach-Iteration 依赖于另一个文件的接口:

export interface IForEachFunction<T> {
    (callback: T): boolean | void;
}

你会像这样使用我的列表和 ForEach-Method:

let myList: List<a_type> = new List<a_type>();
let completed: boolean = myList.ForEach(xyz => {
    // do something with xyz
    return false; // aborts the iteration
    return true; // continues with the next element
});
if (completed) // we can see what happened "during" the iteration

我认为这还不错,但如果有任何意见,我将不胜感激。我不确定我是否正确使用了 ===。 另一个我很想知道的问题:如何使用接口 IForEachFunction 定义函数?我并没有真正“重用”该接口,我总​​是声明一个匿名方法,如上所示。如果我想调用具有接口定义的方法,可以吗?

谢谢! 拉尔夫

【问题讨论】:

  • FWIW, Array#every 和你的 ForEach 方法一样。我会坚持使用普通数组而不是编写包装器。
  • 这个问题似乎有点太宽泛了,因为我不知道如何给出一个不能解决所有不同问题的独立答案:你的 ForEach 函数看起来不错。您对=== 的使用很好。您可以使用如下接口定义定义函数:var forEachFunc: IForEachFunction&lt;string&gt; = function(s) { return !!s; }。方法和属性通常以小写字母开头。我假设您实现 List 类是为了充实自己,而不是在“现实世界”中使用,因为正如其他人所说,在大多数情况下最好使用 js 数组。

标签: list typescript collections


【解决方案1】:

我看到的一个问题是你有一个接口实例:

callback: IForEachFunction<T>

这包含一个名为

的方法
callback()

但是你只调用一次回调。您将在界面中调用 callback() 方法:

callback.callback()

您的代码看起来也是受 C# 或 Java 启发的。在 TypeScript 中,您通常只使用一个数组。这简化了某些代码结构。

【讨论】:

  • 不,IForEachFunction&lt;T&gt; 不包含名为 callback 的方法。它是一个可调用的类函数接口,带有一个名为callback参数。仔细查看括号的位置。
  • 他的困惑表明@Ralf 的声明比它需要的更令人困惑:callback 参数不是回调;它只是一个T 类型的值;没有其他属性的可调用接口本质上只是一个函数类型。我建议改用export type IForEachFunction&lt;T&gt; = (t: T) =&gt; boolean | void; 之类的东西,它的作用或多或少相同并且更清晰。
猜你喜欢
  • 1970-01-01
  • 2014-07-01
  • 2010-10-03
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
相关资源
最近更新 更多