sampleDocument不可分配给T类型

时间:2020-01-23 06:24:02

标签: javascript typescript oop

我是TypeScript的新手,正在尝试将它与OOP结合使用。

我有以下代码:

import {ReadOnlyDocument} from "../../docs/read-only.document";
import {IReadOnlyRepository} from "./abstract/Iread-only.repository";
import {sampleDocument} from "../../docs/sampleDocument";

export abstract class ReadOnlyRepository<T extends ReadOnlyDocument> implements IReadOnlyRepository<T> {

    public getById(id: string): T {
        let sample: sampleDocument = new sampleDocument('',
            new Date(),
            '',
            new Date(),
            '');
        /*Line of code that brings the error.*/
        return sample;
    }

}

但是我一直收到错误消息 sampleDocument不能分配给T类型,而且我似乎无法弄清楚出什么问题了。任何帮助将不胜感激。

我在下面添加了其他可能相关的代码。

import {ReadOnlyDocument} from "./read-only.document";

export class sampleDocument extends ReadOnlyDocument{

}
export abstract class Document {
    constructor(
        public id: string,
        public createdDate: Date,
        public createdBy: string,
        public updatedDate: Date,
        public updatedBy: string
    ) { }
}
import { Document } from './abs/document'

export abstract class ReadOnlyDocument extends Document{

}
import {ReadOnlyDocument} from "../../../docs/read-only.document";
import { IRepository } from "./Irepository";

export interface IReadOnlyRepository<T extends ReadOnlyDocument> extends IRepository<T> {
    getById(id: string): T;
}
import {Document} from "../../../domain/documents/abstract/document";

export interface IRepository<T extends Document>  {

}

1 个答案:

答案 0 :(得分:0)

TReadOnlyDocument的任何子类型,例如如果您有一个ReadOnlyPDF并且扩展了ReadOnlyDocument,则可以构造一个ReadOnlyRepository<ReadOnlyPDF>,并且希望它从ReadOnlyPDF返回一个getById,但是仅返回ReadOnlyDocument