0

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> {}

1 Answer 1

1

Actually, it seems like it's possible

interface ModelConstructor<M, D> { new (document: D): M & D }

abstract class Model<D> {
  constructor(document: D) { Object.assign(this, document) }
}

function buildModel<D extends Object>(): ModelConstructor<Model<D>, D> {
  return Model as any
}

interface PostDocument {
  id:   number
  text: string
}

class Post extends buildModel<PostDocument>() {
}

const document: PostDocument = { id: 5, text: 'something' }
const post = new Post(document)
console.log(post.text)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.