You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错:Promise<Loaded<Post, never> | null>不存在title属性

问题描述

学习Ben Awad的YouTube课程时,实现update mutation功能遇到TypeScript错误:

Property 'title' does not exist on type 'Promise<Loaded<Post, never> | null>'.ts(2339)

具体代码如下:

@Mutation(() => Post, { nullable: true })
async updatePost(
    @Arg("_id") _id: number,
    @Arg("title", () => String, { nullable: true }) title: string,
    @Ctx() { em }: MyContext
): Promise<Post | null> {
    // Fetch post
    const post = em.findOne(Post, { _id });
    // If unable to find post
    if (!post) {
        return null;
    }
    if (typeof title !== "undefined") {
        post.title = title;
        await em.persistAndFlush(post);
    }
    return post;
}

推测是ORM版本差异导致(视频为2020年内容),作为TypeScript新手,不清楚如何处理这个Promise类型的“解包”问题,寻求帮助与解释。

解决方案与解释

  • 核心问题:em.findOne()是异步方法,返回的是Promise<Loaded<Post, never> | null>,而非直接的Post实例。直接操作Promise对象自然无法访问title属性。
  • 修复代码:在em.findOne()前添加await关键字,等待Promise resolve后拿到实际的Post实例或null:
    // 加上await获取实际的Post实例
    const post = await em.findOne(Post, { _id });
    
  • 逻辑说明:添加await后,post的类型变为Loaded<Post, never> | null,此时if (!post)的判断有效,后续操作post.title也不会再触发TypeScript错误。
  • 版本差异原因:2020年视频中使用的ORM版本(如MikroORM)的findOne是同步方法,而当前版本已改为异步实现,因此必须通过await处理返回的Promise。

内容的提问来源于stack exchange,提问作者vls9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:26:16