typescript 如何在TS中从基类到子类指定类属性的类型?

kb5ga3dv  于 2022-12-30  发布在  TypeScript
关注(0)|答案(1)|浏览(212)

下面的代码:

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
    }
}

尽管我在构造函数(User)中指定了集合项的具体类型,但是当我在foo()中处理集合时,typescript认为我仍然在处理ICollection<object>类型的集合,而不是ICollection<User>

const _collection = this.collection as ICollection<User>

但是在每个方法中都这样做显然是个坏主意。我如何在Child类中指定属性collectionICollection<User>类型?或者我应该简单地覆盖基类的属性?这似乎也不是个好主意

9wbgstp7

9wbgstp71#

利用类型参数的可能解决方案:

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> 
    }
}

相关问题