我正在嘗試有條件地訪問我的 TypeScript 代碼中的貓鼬模型。任何人都知道如何修復這個 TypeScript 錯誤?
Each member of the union type has signatures, but none of those signatures are compatible with each other
.find() 在條件模型上拋出錯誤。
interface PictureDocument extends Document {
paint: string;
}
interface VideoDocument extends Document {
duration: number;
}
const PictureSchema = new Schema<PictureDocument>({ paint: String });
const VideoSchema = new Schema<VideoDocument>({ duration: Number });
const PictureModel = model<PictureDocument>("video", PictureSchema);
const VideoModel = model<VideoDocument>("video", VideoSchema);
const MY_CONDITION = "picture";
const getDocuments = async (condition: "picture" | "video") => {
const model = condition === "picture" ? PictureModel : VideoModel; // <--- Here I conditionally get my model to execute queries on
return await model.find().exec(); // <--- .find() throws TS error here
};
getDocuments(MY_CONDITION);
This expression is not callable.
Each member of the union type '{ (callback?: ((err: any, res: VideoDocument[]) => void) | undefined): DocumentQuery<VideoDocument[], VideoDocument, {}>; (conditions: FilterQuery<...>, callback?: ((err: any, res: VideoDocument[]) => void) | undefined): DocumentQuery<...>; (conditions: FilterQuery<...>, projection?: any, callback?: ((err: any, res:...' has signatures, but none of those signatures are compatible with each other.
uj5u.com熱心網友回復:
好的,實際上它很簡單,我認為它是 TypeScript 中聯合型別問題的常見解決方案
const model: Model<PictureDocument | VideoDocument> = condition === "picture" ? PictureModel : VideoModel;
通過將型別添加到變數宣告中,解決了聯合型別問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/372640.html
