My goal is to develop a function that accepts a mongoose model instance as its sole parameter. In order to achieve this, I am looking to specify the Type like so:
function getModelInstance(instance: TypeToBeDetermined) {
// actual implementation does not matter
}
Below is my code for creating the Schema and Model:
interface Product {
name: string,
}
const productSchema = new mongoose.Schema<Product>({
name: String,
});
const ProductModel = mongoose.model('Product', productSchema);
My attempt at achieving this functionality:
// although the type is automatically inferred, it is not practical:
// mongoose.Model<Product, {}, {}, {}, mongoose.Document<unknown, {}, Product> & Omit<Product & { _id: mongoose.Types.ObjectId; }, never>, any>
const example1 = new ProductModel();
// no immediate error is generated, but features such as autocompletion with `example.name` do not work indicating an issue
const example2: typeof ProductModel = new ProductModel();
Update: The problem was resolved by using
const example3: InstanceType<typeof ProductModel> = new ProductModel();
If there are simpler solutions available, please share them! Thank you.