Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.97k stars 3.84k forks source link

Add generic type for Model constructor #10074

Closed imduchy closed 3 years ago

imduchy commented 3 years ago

Would it be possible to change doc type to a generic type Z, where T = Z & Document?

https://github.com/Automattic/mongoose/blob/9e98cd82f31ac97c50fde42a24ca75f800fc1550/index.d.ts#L604

That way we could get a proper type inference when creating new documents. An example:

interface IDog {
  breed: string;
  name: string;
  age: number;
}

type IDogDocument = IDog & Types.Document;

const DogSchema = new Schema<IDogDocument>(
  {
    breed: { type: String },
    name: { type: String },
    age: { type: Number }
  }
)

const Dog = mongoose.model<IDogDocument, Model<IDogDocument>>('dog', DogSchema)

const rex = new Dog({
  // type inference here 
})

// or alternatively 
const rex = new Dog<IDog>({
  // type inference here
})
vkarpov15 commented 3 years ago

I'd say this is by design. Mongoose does allow you to pass in arbitrary data into the Model constructor.

Would the new Dog<IDog>({ ... }) syntax work for your case?

imduchy commented 3 years ago

Yeah, I think that would be good enough.