【问题标题】:How to add constructor for and class which is extending an generic class in typescript?如何为在打字稿中扩展泛型类的类添加构造函数?
【发布时间】:2017-05-08 15:30:05
【问题描述】:

我在打字稿中有一个通用类,如下所示:

export class Result<T> {
    public ErrorMessage: string;
    public Data: T;

    constructor() {
        this.ErrorMessage = '';
        this.Data = null;
    }
}

然后有另一个类扩展第一个类:

export class ResultList<T> extends Result<T> {
    public TotalCount: number;

    // how to place constructor which calls the base constructor?
}

在这种情况下,我需要一个子类的构造函数“ResultList”,我该如何创建这个构造函数?

【问题讨论】:

    标签: javascript generics typescript inheritance


    【解决方案1】:

    你只需声明它并让它调用super

    export  class ResultList<T> extends Result<T> {
        public TotalCount: number;
    
        constructor() {
            super();
            this.TotalCount = 0; // Or whatever
        }
    }
    

    如果你想让它传递它的参数,你可以使用rest和spread notation来做到这一点:

    constructor(...args) {
        super(...args);
        this.TotalCount = 0; // Or whatever
    }
    

    请注意,对super 的调用必须在允许对this 进行任何访问之前发生。

    【讨论】:

    • 哇,我能说什么,我很惭愧没有尝试这么简单的事情。
    • @EhsanErshadi:LOL 有时它比你想象的要容易。 :-)
    猜你喜欢
    • 2019-07-05
    • 2017-01-29
    • 2021-10-04
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多