【问题标题】:sampleDocument is not assignable to type TsampleDocument 不可分配给类型 T
【发布时间】:2020-01-23 06:24:02
【问题描述】:

我是 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 is not assignable to type 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>  {

}

【问题讨论】:

    标签: javascript typescript oop


    【解决方案1】:

    TReadOnlyDocument 的任何子类型,例如如果你有一个ReadOnlyPDF 并且扩展了ReadOnlyDocument,那么你可以构造一个ReadOnlyRepository&lt;ReadOnlyPDF&gt;,并且你希望它从getById 返回一个ReadOnlyPDF,但是它只返回一个ReadOnlyDocument

    【讨论】:

    • 有道理,所以我怎样才能拥有它以便我可以创建并返回一个新的泛型类型(在这种情况下为sampleDocument),但还要确保它是抽象类型 ReadOnlyDocument?我在here 阅读了有关传递构造函数的信息。但它并没有说明如果您的构造函数需要将参数传递给它,那将如何工作。
    • @kikanye 我建议省略泛型类型,然后也省略方法的返回类型。
    猜你喜欢
    • 2022-11-11
    • 2022-11-11
    • 2020-10-28
    • 2021-11-16
    • 2016-07-31
    • 2017-12-29
    • 2019-01-31
    • 2019-11-17
    • 2018-09-19
    相关资源
    最近更新 更多