Skip to content

TypeScript does not complain about type issues when returning doc.toObject() #12883

@twiddler

Description

@twiddler

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

6.8.3

Node.js version

n/a

MongoDB server version

n/a

Typescript version (if applicable)

4.9.4

Description

I am having a hard time understanding why TypeScript complains in getUser_1 and getUser_3 seen below, but not in getUser_2.

Is this an issue with mongoose?

Steps to Reproduce

import mongoose from 'mongoose'

const userSchema = new mongoose.Schema({
    name: String,
})

const UserModel = mongoose.model('User', userSchema)

type GetUserOutput = {
    _id: string
    firstname?: string
}

async function getUser_1(): Promise<GetUserOutput> {
    const user = await UserModel.findOne({}).exec()

    if (user === null) throw new Error(`No user found.`)

    return user // TypeScript complains:
    // Type 'Document<unknown, any, { name?: string | undefined; }> & { name?: string | undefined; } & { _id: ObjectId; }' is not assignable to type 'GetUserOutput'.
    //   Types of property '_id' are incompatible.
    //     Type 'ObjectId' is not assignable to type 'string'.ts(2322)
}

async function getUser_2(): Promise<GetUserOutput> {
    const user = await UserModel.findOne({}).exec()

    if (user === null) throw new Error(`No user found.`)

    return user.toObject() // TypeScript does not complain.
}

async function getUser_3(): Promise<GetUserOutput> {
    const user = await UserModel.findOne({}).exec()

    if (user === null) throw new Error(`No user found.`)

    const o = user.toObject()

    return o // TypeScript complains:
    // Type 'LeanDocument<{ name?: string | undefined; }> & { _id: ObjectId; }' is not assignable to type '{ firstname?: string | undefined; _id: string; }'.
    //   Types of property '_id' are incompatible.
    //     Type 'ObjectId' is not assignable to type 'string'.ts(2322)
}

Expected Behavior

TypeScript should complain in getUser_2, too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    typescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions