'Mongoose 5.11.11 SchemaDefinition Typing

Mongoose recently updated to accept a model generic it works well with a string type but not with a boolean type. Type 'boolean' is not assignable to type 'SchemaDefinitionProperty<undefined>'.

interface User {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
  isVerified?: boolean;
}

const UserSchemaDefinition: SchemaDefinition<User> = {
  firstName: {
    type: String,
    trim: true,
    required: true,
  },
  lastName: {
    type: String,
    trim: true,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
    private: true,
  },
  isVerified: {
    type: Boolean,
    default: false,
  },
};

const UserSchema = new mongoose.Schema(UserSchemaDefinition); // Typescript complains here.

Example is posted here https://github.com/Automattic/mongoose/pull/9761



Solution 1:[1]

(parameter) definition: mongoose.SchemaDefinition<T>
Argument of type 'SchemaDefinition<T>' is not assignable to parameter of type 'SchemaDefinition<SchemaDefinitionType<T>> | undefined'.
  Type '{ [path: string]: SchemaDefinitionProperty<undefined>; } | { [path in keyof T]?: SchemaDefinitionProperty<T[path]> | undefined; }' is not assignable to type 'SchemaDefinition<SchemaDefinitionType<T>> | undefined'.
    Type '{ [path: string]: SchemaDefinitionProperty<undefined>; }' is not assignable to type 'SchemaDefinition<SchemaDefinitionType<T>>'.
      Type '{ _id?: SchemaDefinitionProperty<any> | undefined; __v?: SchemaDefinitionProperty<any> | undefined; $getAllSubdocs?: SchemaDefinitionProperty<...> | undefined; ... 52 more ...; validateSync?: SchemaDefinitionProperty<...> | undefined; }' is not assignable to type 'SchemaDefinition<SchemaDefinitionType<T>>'.

import mongoose, {
  model, Schema, Model, Document, SchemaDefinition,
} from 'mongoose';

const express = require('express');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');

interface IUser extends Document {
  email: string;
  firstName: string;
  lastName: string;
}

interface IDocUser extends mongoose.Document, IUser { }

interface UserSchemaProps {
  email: typeof String;
  firstName: typeof String;
  lastName: typeof String;
}

function createSchema<T extends mongoose.Document>(definition: SchemaDefinition<T>) {
  return new Schema<T>(definition);
}

const UserSchemaDefinition: mongoose.SchemaDefinition = {
  email: { type: String, required: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
};

const UserSchema: Schema<IDocUser> = createSchema<UserSchemaProps>(UserSchemaDefinition);

any solution?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sugan suganth