带有继承的打字稿编译器错误泛型类型

Typescript compiler error generic type with inheritance

由于 output 变量中的键入错误,以下代码无法编译:

Type '{ item: ModelInterface; }' is not assignable to type 'ResponseInterface'. Types of property 'item' are incompatible. Type 'ModelInterface' is not assignable to type 'T'.

interface ModelInterface {

}

interface ResponseInterface<T> {
    item: T;
}

class Store {
    get<T extends ModelInterface>(): ResponseInterface<T> {
        let output: ResponseInterface<T> = {
            item: this.getModel()
        };
        return output;
    }

    getModel(): ModelInterface {
        return null;
    }
}

get 方法显式定义 T 将始终扩展 ModelInterface,为什么我不能将显式 ModelInterface 对象设置为 item出错了?

我可以通过以下方式克服这个错误:

let output: ResponseInterface<T> = {
    item: this.getModel() as T
};

但它看起来像一个错误,我遗漏了什么或者打字稿编译器在这种情况下只是失败了?

我试过 typescript playground 但也失败了。

有什么想法吗?

TModelInterface 扩展的事实确实确保任何 T 实例都可以 "cast" 到 ModelInterface。但这并不意味着其他。

例如:

class ModelInterface
{
    public name: string;
}

interface ResponseInterface<T> {
    item: T;
}

class ModelInterfaceExtended
{
    public name: string;
    public age: number;
}

class Store
{
    get<T extends ModelInterface>(): ResponseInterface<T> {
        let output: ResponseInterface<T> = {
            item: this.getModel()
        };
        return output;
    }

    getModel(): ModelInterface {
        return null;
    }
}

const s = new Store();
let result = s.get<ModelInterfaceExtended>();

这里 result 将有 属性 个类型为 ModelInterfaceExtended 的项目,属性为 nameage。而 getModel 不能创建这样的对象,因为它 return 类型是 ModelInterface - 只有 name

您可以通过进行以下更改来修复它:

class ModelInterface
{
    public name: string;
}

interface ResponseInterface<T> {
    item: T;
}

class ModelInterfaceExtended
{
    public name: string;
    public age: number;
}

class Store<T extends ModelInterface>
{
    get(): ResponseInterface<T>
    {
        return {
            item: this.getModel()
        };
    }

    getModel(): T
    {
        return null;
    }
}

const s = new Store();
let result = s.get();