0

I came across this question and would like to customize my code in a similar way, except using typescript and a more complicated object.

For example I have the type:

export type ImportationType = {
  commercialImportation: boolean
  dateToManufacturer: string
  barrels: {
    assumedAmount: number
    sealId: string
    uniqueIdentifier?: string
    dateShipped?: string
    dateImported?: string
  }[]
}

And now I would like to extend the barrels object to have an id: number type.

So it would be:

export type UpdatedImportationType = {
  commercialImportation: boolean
  dateToManufacturer: string
  barrels: {
    id: number
    assumedAmount: number
    sealId: string
    uniqueIdentifier?: string
    dateShipped?: string
    dateImported?: string
  }[]
}

Currently I'm doing the following:

type UpdatedImportationType: Omit<ImportationType, "barrels"> & {
  barrels: {
    id: number
    assumedAmount: number
    sealId: string
    uniqueIdentifier?: string
    dateShipped?: string
    dateImported?: string
  }[]
}

It seems like there should be a better way of adding the id field without needing to rewrite the whole type for barrels.

Something like

// Attempt 1
UpdatedImportationType: Omit<ImportationType, "barrels"> & {
  barrels: {
    ...ImportationType["barrels"], // does not work
    id: number
  }[]
}

//Attempt 2
UpdatedImportationType: ImportationType & {
  barrels: {
    id: number
  }[] // creates two `barrels[]` on the type one with id one with all the other fields.
}

Can someone show me the Typescript "magic" that I don't yet know to solve this?

Shadoath
  • 720
  • 1
  • 15
  • 31
  • Does [this approach](https://tsplay.dev/wQb3JN) work for you? If yes, I'll write an answer explaining; If not, what am I missing? – wonderflame Aug 18 '23 at 13:18
  • @wonderflame It appears to be what I want. Can you add comments explaining the code? – Shadoath Aug 19 '23 at 02:51
  • I see that you've accepted the other answer. Should I write the answer? – wonderflame Aug 19 '23 at 16:53
  • I think your approach was a possible solution, however, it seemed complicated and didn't provide an explanation for what was going on. – Shadoath Aug 21 '23 at 18:15
  • The explanation is provided during the answer, not in the comments. My approach was generic and I thought that was what you were looking for – wonderflame Aug 21 '23 at 18:24

1 Answers1

2

Something like this?


type BarrelWithId = ImportationType['barrels'][number] & {id: number}
type WithId = Omit<ImportationType, "barrels"> & {barrels: BarrelWithId[]}
ertucode
  • 560
  • 2
  • 13