TypeScript 泛型问题,求解

我有一个抽象泛型类,想在抽象类中做一些预处理,大概如下面的例子:

interface BResponse {
    succcess: boolean,
    message: string,
}

interface MyResponse extends BResponse {
    data: any,
}

abstract class BaseTask<T extends BResponse> {
    protected constructor() {
        this.init();
    }

    init() {
        this.runTask({ succcess: false, message: 'fucking shit' });
    }

    runTask(resp: T) {
        console.log(resp);
    }
}

我想在父类中调用runTask()这个方法传入一些基类的数据,但是编译阶段代码就报错下面的错误:

TS2345: Argument of type '{ succcess: false; message: string; }' is not assignable to parameter of type 'T'.   '{ succcess: false; message: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'BResponse'.

image.png

我想请问,我该如何在父类中能够调用 runTask()方法?

阅读 1.3k
1 个回答

断言一下:

this.runTask({ succcess: false, message: 'fucking shit' } as T);

P.S. 通篇的 success 都有拼写错误。