Ehsan Zargar Ershadi
Ehsan Zargar Ershadi

Reputation: 24833

How to add constructor for and class which is extending an generic class in typescript?

I have a generic class in typescript as bellow:

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

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

Then have another class which extends the first one:

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

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

I need to have a constructor for the child class in this case "ResultList", How could i create this constructor?

Upvotes: 0

Views: 53

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075019

You just declare it and have it call super:

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

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

If you want it to pass along its arguments, you can use rest and spread notation to do that:

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

Note that the call to super must occur before any access to this is allowed.

Upvotes: 3

Related Questions