Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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'
    }]
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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'
  }]
}
about 4 years ago · Juan Pablo Isaza Relatório

0

you can use extends keyword for extend existing interface

interface ListWithId extends List {
  id: string;
}

or you can make id optional in existing List interface so if you already used it some where it was not affect any one.

interface List {
  name: string;
  id?: string;
}

Note: ? is used to make property optional.

about 4 years ago · Juan Pablo Isaza Relatório

0

to add alternative approach to previous answers

type ListWithId = List & {id: string};

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

or, not pretty but works

interface ListData {
    type: string
    lists: (List & {id: string})[] //how to include id here?
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda