dimanche 10 janvier 2021

Best way to create entity objects with TypeScript?

I'm just getting started with TypeScript and wanted to know if this is the best approach on initializing entity objects with data coming from an API.

How I did it before with JavaScript:

class Entity {
  constructor(apiResponseData = {}) {
    this.id = apiResponseData.id
    this.set = apiResponseData.set
    ...
  }

  toObject() {
    return { id: this.id, ... }
  }
}

For my approach with TypeScript:

interface EntityData {
  id: string
  set: string,
  ...
}

class Entity {
  id: string
  set: string
  
  constructor(apiResponseData: EntityData) {
    this.id = apiResponseData.id
    this.set = apiResponseData.set
    ...
  }

  toObject() {
    return { id: this.id, ... }
  }
}

Is there a better way to do this in TypeScript? It duplicates a lot of code due to declaring types multiple times and so it gets big the more properties I need to define.

An alternate way I thought of could be:

interface EntityData {
  id: string
  set: string,
  ...
}

interface Entity extends EntityData {
  toObject: () => EntityData
}

const buildEntity = (apiResponseData: EntityData) => {
  return {
    id: apiResponseData.id,
    set: apiResponseData.set,
    ...
    toObject: () => ({ id: apiResponseData.id, ... }) // imagine if method does some other operations to the data
  }
}

My only concern for this approach is if member data is changed (ex. id=1 => id=2 after entity is built), then toObject() will be incorrect.

Any ideas or other approaches?

Aucun commentaire:

Enregistrer un commentaire