node.js - Mongoose + TypeScript: Villkorligt find() dokument på modell ger fel: Unionstyp har signaturer, men ingen är kompatibel med varandra
Jag försöker villkorligt få åtkomst till en mongoose-modell i min TypeScript-kod. Vet någon hur man åtgärdar detta TypeScript-fel? Varje medlem av unionstypen har signaturer, men ingen av dessa signaturer är kompatibla med varandra
.find() på den konditionella modellen ger felet.
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.
Svar #1
Okej, egentligen var det ganska enkelt och det är en vanlig lösning på problem med unionstyper i TypeScript, tror jag
const model: Model<PictureDocument | VideoDocument> = condition === "picture" ? PictureModel : VideoModel;
Genom att lägga till typen i variabeldeklarationen löses problemet med unionstyper.
