如何解决TypeScript中"Object literal may only specify known properties"错误?
解决Next.js + Mongoose中的FilterQuery类型错误
问题分析
你遇到的两个TypeScript错误,本质是FilterQuery的类型参数使用错误:
- 错误1:
'title' does not exist in type 'FilterQuery<Model<any, {}, {}, {}, any, any>>' - 错误2:
'answers' does not exist on type 'FilterQuery<Model<any, {}, {}, {}, any, any>>'
原因是定义query时,你用了FilterQuery<typeof Question>,但typeof Question是Mongoose的Model类型,不是自定义的IQuestion文档接口。FilterQuery需要基于文档的类型(即IQuestion),才能识别文档中的title、answers等属性。
解决方案
将FilterQuery的类型参数从typeof Question改为IQuestion,同时确保已导入IQuestion接口:
修改后的核心代码片段:
// 确保导入IQuestion接口 import Question, { IQuestion } from "@/models/Question"; import { FilterQuery } from "mongoose"; export async function getQuestions(params: GetQuestionsParams) { try { connectToDatabase(); const { searchQuery, filter, page = 1, pageSize = 10 } = params; const skipAmount = (page - 1) * pageSize; // 关键修改:将typeof Question改为IQuestion const query: FilterQuery<IQuestion> = {}; if (searchQuery) { const escapedSearchQuery = searchQuery.replace( /[.*+?^${}()|[\]\\]/g, "\\$&" ); query.$or = [ { title: { $regex: new RegExp(escapedSearchQuery, "i") } }, { content: { $regex: new RegExp(escapedSearchQuery, "i") } }, ]; } let sortOptions = {}; switch (filter) { case "newest": sortOptions = { createdAt: -1 }; break; case "frequent": sortOptions = { views: -1 }; break; case "unanswered": // 现在TypeScript会识别answers属性 query.answers = { $size: 0 }; break; default: break; } // 后续代码保持不变 const questions = await Question.find(query) .populate({ path: "tags", model: Tag }) .populate({ path: "author", model: User }) .skip(skipAmount) .limit(pageSize) .sort(sortOptions); const totalQuestions = await Question.countDocuments(query); const isNext = totalQuestions > skipAmount + questions.length; return { questions, isNext }; } catch (error) { console.log(error); throw error; } }
额外说明
- Mongoose的
FilterQuery<T>泛型要求T是文档接口类型(比如你定义的IQuestion),而不是Model类型。Model类型是用于操作数据库的类,不包含文档的具体属性定义。 - 确保
IQuestion接口正确继承了Mongoose的Document,且所有属性和Schema定义一致,这样TypeScript才能正确推断查询对象的类型。
内容的提问来源于stack exchange,提问作者Muhammadali
相关产品推荐
相关产品推荐

