Create a generic post/put/get in typescript react

150 views Asked by At

So I'm trying to learn writing more generic. I have POST/PUT/DELETE/GET for attatchments together with these entity types (there are also alot more entity types that I will need to add in the future).

This code works, and it is indeed more generic than writing 4 different getAttatchment with hardcorded personnel/workoder etc where it is ${apiType} currently. Some progress made atleast.

But how could I rewrite this even better? I would like to have e.g getAttatchments<T>(EntityType<T> .....) but I don't know how I could write it like that. And ofcourse it need to be typesafe so you don't actually pass entities that does not exist.

export enum EntityType {
  Personnel = 'personnel',
  Workorder = 'workorder',
  Asset = 'asset',
  AssetBooking = 'assetbooking',
}

  async getAttachments(id: string | number, apiType: EntityType) {
    return await this.get<AttachmentDetails[]>(
      `attachment/${apiType}/${id}/attachment`
    )
  }
1

There are 1 answers

0
Damian Green On

What you have already looks fairly generic but I would forgo the enum and use a union type instead. e.g.


type EntityType = 'personnel'|'workorder'|'asset'|'assetbooking'

type AttachmentDetails= any // whatever
// mock implementation
function get<T>( url:string) {
  return ''
}

  function getAttachments<T extends EntityType>(id: string | number, apiType: T) {
    return get<AttachmentDetails[]>(      `attachment/${apiType}/${id}/attachment`    )
  }

Playground