Home:ALL Converter>Reducing an interface in TypeScript

Reducing an interface in TypeScript

Ask Time:2016-09-13T03:08:46         Author:Nepoxx

Json Formatter

I have a mongoose model with an interface declaring it as such:

export interface IUserDocument extends mongoose.Document {
  surname: string;
  lastName: string;
}

export interface IUserModel extends mongoose.Model<IUserDocument> {
  myStaticMethodGoesHere(signature: string): void;
}

and the corresponding mongoose schema:

const UserSchema = new mongoose.Schema({
  surname: {type: String, required: true}, 
  lastname: {type: String, required: true},
})

Now I have to define how my User is structured 2 times already (mongoose schema AND typescript interface), which isn't DRY and is inconvenient. Unfortunately, if I want to use mongoose's lean method, I have to define yet another interface:

export interface ILeanUserDocument {
  _id: mongoose.Types.ObjectId;
  __v: number;
  surname: string;
  lastName: string;
}

This is inconvenient and error prone. Is there a way for my lean interface to extend (I don't know the verb to use here) my IUserDocument interface but remove stuff from it?

Author:Nepoxx,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39457125/reducing-an-interface-in-typescript
yy