【问题标题】:Have the linter recognize the type "Ref <T>" as "T" instead of "ObjectId"让 linter 将类型“Ref <T>”识别为“T”而不是“ObjectId”
【发布时间】:2020-02-01 01:30:37
【问题描述】:

当我有如下课程时:

export class Application{
    @prop({ required: [true, 'app name is required'], unique: true })
    name!: string;

    @prop({ required: [true, 'component is required'], ref: Component})
    component!: Ref<Component>;
}

假设“组件”类具有“名称”属性,我不能这样做:

let app: Application
const appName = 'appTest';
app = await (await this.findOne({ name: appName })).populate('component').execPopulate();
console.log(app.component.name);

因为它给了我以下错误:

Property 'name' does not exist on type 'Ref<Component, ObjectId>'.
Property 'name' does not exist on type 'ObjectId'

有没有办法让 linter 将类型视为 T(来自 Ref&lt;T&gt;)而不是 ObjectId?

【问题讨论】:

    标签: node.js typescript nestjs mongoose-populate typegoose


    【解决方案1】:

    目前,对我来说效果很好的是使用类型保护,特别是来自 Typegoose 的 isDocument and isDocumentArray。 应该是这样的:

    let app: Application
    const appName = 'appTest';
    app = await (await this.findOne({ name: appName })).populate('component').execPopulate();
    if (isDocument(app.component)) {
    console.log(app.component.name);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-12
      • 2015-04-24
      • 2021-07-19
      • 2021-03-30
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多