Home > OS >  How to specify the type of class properties from a base class in a child class in TS?
How to specify the type of class properties from a base class in a child class in TS?

Time:01-04

I have the following code:

class Base {
    protected collection: ICollection<object>

    public constructor(collection: ICollection<object>) {
        this.collection = collection
    }
}

class Child extends Base {
    public constructor(collection: ICollection<User>) {
        super(collection)
    }

    private foo(): void {
        // working with collection
    }
}

Although I specified a concrete type of the collection items in the constructor (User), when I work on the collection inside foo(), typescript thinks that I'm still working with the collection of type ICollection<object>, not with ICollection<User>. Currently I'm using a workaround like this inside foo()

const _collection = this.collection as ICollection<User>

But its obviously a bad idea to do it in every method. How can I specify in the Child class that the property collection is of type ICollection<User>? Or should I simply override the property of the base class? It seems also as not the best idea

CodePudding user response:

A possible solution that exploits a type parameter:

class Base<B extends object> {
    protected collection: ICollection<B>

    public constructor(collection: ICollection<B>) {
        this.collection = collection
    }
}

class Child extends Base<User> {
    public constructor(collection: ICollection<User>) {
        super(collection)
    }

    private foo(): void {
        this.collection; // <-- has type ICollection<User> 
    }
}
  • Related