Omit extended typescript typing

Asked

Viewed 41 times

3

When using the Mongoose library, typing a model can be done with an interface that extends the type mongoose.Document. This approach is working according to the example below:

import mongoose from 'mongoose';

export interface IModel extends mongoose.Document {
  name: string;
}

const ModelSchema = new mongoose.Schema({
  Name: { type: String },
});

export default mongoose.model<IModel>('model', ModelSchema);

In creating a function that is able to create a document based on that model, should send an object that has the typing exactly equal to the interface defined within the model, but without the extended properties of mongoose.Document. The question is: Is there any way to delete or omit the extended properties of mongoose.Document?

Below is an example of the function made to create a document:

import Model from 'models/Model';

export default async function createModelDocument(documentData: TIPO_SEM_AS_PROPRIEDADES_ESTENDIDAS): Promise<void> {
  await Model.create(item);
}

1 answer

3


One option is to simply create separate types. One for dice to be stored in the model (as ModelData) and the other which, in fact, represents the model, formed from the intersection of ModelData and mongoose.Document.

Something like that:

interface ModelData {
  name: string;
}

type Model = ModelData & mongoose.Document;

Learn more about the intersection types in documentation typescript.

Then you could use it as follows.

  • To create the template:

    export default mongoose.model<Model>('model', ModelSchema);
    
  • To create a function that depends only on model data:

    import Model, { ModelData } from 'models/Model';
    
    export default async function createModelDocument(documentData: ModelData): Promise<void> {
      await Model.create(item);
    }
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.