【问题标题】:How to export function as a class?如何将函数导出为类?
【发布时间】:2017-02-20 22:50:46
【问题描述】:

我想使用附加方法 get 创建一个基于数组的类。
最初我的代码是这样的:

export class CircularArray extends Array<string> {
    constructor(data: string[]) {
        super();
        this.push(...data);
    }

    get(i: number): string {
        return this[i % this.length];
    }
}

在 typescript 2.0.10 中它运行良好。但是当我决定将 typescript 更新到实际版本 2.2.0 时,我发现此代码的编译 have changed:现在 typescript 处理从 super() 调用返回的值:

function CircularArray(data) {
    var _this = _super.call(this) || this;
    _this.push.apply(_this, data);
    return _this;
}

所以返回的对象是调用Array 的结果。当然,它的原型是Array.prototype 而不是CircularArray.prototype,并且方法get 丢失了。我该如何解决?

我尝试过这样做:

export declare class CircularArray extends Array<string> {
    constructor(data: string[]);
    get(i: number): string;
}

export function CircularArray(data: string[]): CircularArray {
    this.push(...data);
    return this;
};

CircularArray.prototype = Object.create(Array.prototype);

CircularArray.prototype.get = function (i: number): string {
    return this[i % this.length];
};

但出现错误:

错误 TS2300:重复标识符“CircularArray”。
错误 TS2300:重复标识符 'CircularArray'。

PS:Same question in Russian.

【问题讨论】:

    标签: inheritance typescript


    【解决方案1】:

    找到解决办法:

    export interface CircularArray extends Array<string> {
        constructor(data: string[]): CircularArray;
        get(i: number): string;
    }
    
    export var CircularArray: { new (data: string[]): CircularArray } = function CircularArray(data: string[]): void {
        this.push(...data);
    } as any;
    
    CircularArray.prototype = Object.create(Array.prototype);
    
    CircularArray.prototype.get = function (i: number): string {
        return this[i % this.length];
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2016-11-27
      • 2018-09-30
      • 2015-01-05
      相关资源
      最近更新 更多