Skip to content
Advertisement

extend typescript array of object without modifying the source

I have this List object, but later on the shape changed, I need an extra id property, but how to not modify List?

interface List {
    name: string //without adding id here
}

interface ListData {
    type: string
    lists: List[] //how to include id here?
}

const data: ListData = {
    type: 'something',
    lists: [{
        id: '1',
        name: 'alice'
    }, {
        id: '2',
        name: 'ja'
    }]
}

Advertisement

Answer

You can extend the List interface

interface List {
  name: string //without adding id here
}

interface ListId extends List {
  id: string
}

interface ListData {
  type: string
  lists: ListId[]
}

const data: ListData = {
  type: 'something',
  lists: [{
    id: '1',
    name: 'alice'
  }, {
    id: '2',
    name: 'ja'
  }]
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement