I'm implementing Data Models for Database with TypeScript, and the code looks really ugly and verbose, is there any shorter version to declare it?
It's for MongoDB, so I would like to have an Interface for raw MongoDB document and the Model class separately. The ugly but working version looks like that
interface PostDocument {
id: number
text: string
}
class Post implements PostDocument {
id: number
text: string
constructor(doc: PostDocument) {
this.id = doc.id
this.text = doc.text
}
}
Ideally would be nice to have something like the code below, but I don't know if something like that possible with TypeScript
class Model<D> {
somehow declare properties from D on Model
constructor(document: D) { Object.assign(this, document) }
}
interface PostDocument {
id: number
text: string
}
class Post extends Model<PostDocument> {}