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
相关产品推荐
相关产品推荐

