Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add generic type for Model constructor #10074

Closed
imduchy opened this issue Mar 27, 2021 · 2 comments · Fixed by #10165
Closed

Add generic type for Model constructor #10074

imduchy opened this issue Mar 27, 2021 · 2 comments · Fixed by #10165
Assignees
Labels
typescript Types or Types-test related issue / Pull Request
Milestone

Comments

@imduchy
Copy link
Contributor

imduchy commented Mar 27, 2021

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

new(doc?: any): T;

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
})
@IslandRhythms IslandRhythms added new feature This change adds new functionality, like a new method or class typescript Types or Types-test related issue / Pull Request labels Mar 29, 2021
@vkarpov15
Copy link
Collaborator

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?

@vkarpov15 vkarpov15 added discussion If you have any thoughts or comments on this issue, please share them! and removed new feature This change adds new functionality, like a new method or class labels Apr 12, 2021
@imduchy
Copy link
Contributor Author

imduchy commented Apr 12, 2021

Yeah, I think that would be good enough.

@vkarpov15 vkarpov15 added this to the 5.12.5 milestone Apr 17, 2021
@vkarpov15 vkarpov15 removed the discussion If you have any thoughts or comments on this issue, please share them! label Apr 17, 2021
@vkarpov15 vkarpov15 modified the milestones: 5.12.5, 5.12.6 Apr 19, 2021
@vkarpov15 vkarpov15 assigned IslandRhythms and unassigned vkarpov15 Apr 19, 2021
@IslandRhythms IslandRhythms linked a pull request Apr 21, 2021 that will close this issue
vkarpov15 added a commit that referenced this issue Apr 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
typescript Types or Types-test related issue / Pull Request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants