【问题标题】:Get type right when nesting Mongoose models in Typescript using interfaces使用接口在 Typescript 中嵌套 Mongoose 模型时获取正确的类型
【发布时间】:2016-09-13 06:58:19
【问题描述】:

我有一个带有 Mongoose 模式接口的模块,如下所示:

// Interface
export interface User extends PassportDocument
{
    person: ObjectId | Person
}

// Mongoose Schema
var schema = new PassportSchema({
    person: { type: ObjectId, required: false, ref: 'Person' }
};

我的问题是,当我在 User 文档上填充 person 时,我不明白如何正确输入。

.then((user: User) => {
  console.log(user.person._id); // Property '_id' does not exist on type 'ObjectId | Person'
}

如何解决这个问题,以便在不创建新接口的情况下仍然可以使用类型?

【问题讨论】:

    标签: mongoose typescript


    【解决方案1】:

    你想要user defined type guards.

    假设人员界面是包含 _id 属性的界面,

    function isPerson(potentialPerson:any) : potentialPerson is Person {
        // person-checking logic.
    }
    
    .then((user: User) => {
        if(isPerson(user.person)) {
            console.log(user.person._id); // should work now, user.person is understood to be of type 'Person'
        }
    }
    

    【讨论】:

    • 您在参数后面忘记了:,它少于 6 个字符,所以我无法编辑它。否则它就像一种享受,所以谢谢你!现在我只需要弄清楚为什么 Gulp 给我一个错误,尽管一切正常......
    • 我的 linter 不再给我任何警告,但是在编译时我得到了activities.ts(105,91): error TS2339: Property '_id' does not exist on type 'ObjectId | Person'.。运行它时,尽管在应用程序本身中,一切都正常工作。任何想法发生了什么?
    • @Oskar 啊,你是对的,谢谢。我已经更新了代码。至于您的第二条评论,您是否继续在 if 语句的代码块中访问它?它仅被确认为 Person 类型。该范围之外的 var 类型不会改变。
    • 是的,我做了类似于var personId = typeDefHelpers.isPerson(user.person) ? user.person._id : null的事情。
    • 您使用的是什么版本的打字稿?我相信这些出现在 1.6 中。
    猜你喜欢
    • 2020-01-01
    • 1970-01-01
    • 2021-10-17
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2017-07-06
    相关资源
    最近更新 更多