-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Closed
Labels
typescriptTypes or Types-test related issue / Pull RequestTypes or Types-test related issue / Pull Request
Milestone
Description
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.
alukach
Metadata
Metadata
Assignees
Labels
typescriptTypes or Types-test related issue / Pull RequestTypes or Types-test related issue / Pull Request