Home > database >  Mongoose TypeScript: Conditionally find() documents on model throws error: Union type has signatur
Mongoose TypeScript: Conditionally find() documents on model throws error: Union type has signatur

Time:12-03

I'm trying to conditionally access a mongoose model in my TypeScript code. Anyone knows how to fix this TypeScript error? Each member of the union type has signatures, but none of those signatures are compatible with each other

.find() on the conditional model throws the error.


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.

CodePudding user response:

Okay actually it was quite simple and it is a common solution to union type problems in TypeScript I think

const model: Model<PictureDocument | VideoDocument> = condition === "picture" ? PictureModel : VideoModel;

By adding the type to the variable declaration, the union type problem is solved.

  • Related