0

当我有如下课程时:

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<T>)而不是 ObjectId?

4

1 回答 1

1

目前,对我来说效果很好的是使用类型保护,特别是 Typegoose 的isDocument 和 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);
}
于 2020-01-31T17:30:37.217 回答