DEV Community

Discussion on: How can I reduce amount of boilerplate code while working with TypeScript+mongoose 🙈

 
nickytonline profile image
Nick Taylor

You can even go a bit further.

interface BaseEntity {
  id: string;
  createdAt: Date;
}

type Entity<T> = T & BaseEntity;

interface Vehicle {
  model: string;
  year?: string;
  seatsCount?: number;
}

// Enforce having the bare minimum entity properties
type MongooseDocument<T extends BaseEntity> = T & mongoose.Document;

const dbDocument: MongooseDocument<Entity<Vehicle>> = {
  SomeMongooseDocProperty: "yolo",
  createdAt: new Date(),
  id: "5FCA1C32-1D92-47CA-A885-A5A747E6E4FB",
  model: "Mini",
  seatsCount: 4,
  year: "1999"
};

See the updated playground example