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

97
Visualizações
Typescript merging two object with spread operator and having a resuable type

Hopefully this is a simple enough question but I am having trouble figuring out how to word it in the title. I was making a function that gets and sets a value. And for the setting of the value I basically have to rewrite the initial type but with a question mark next to it because I will be automatically merging the current variables with the new ones.

Is there a simpler approach that allow you to dynamically add the question mark to this or is this the way to go about it? Because I want the original variables to be required in the Vars type.

So a simple example like:

interface Vars {
  a: number
  b: number
}

interface NewVars {
  a?: number
  b?: number
}

const createVars = () => {
  let vars: Vars = {
    a: 1,
    b: 2
  }

  const get = () => vars

  const set = (newVars: NewVars) => {
    vars = {
      ...vars,
      ...newVars
    }
  }

  return {
    get,
    set
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the Partial utility type

interface NewVars extends Partial<Vars> {}

//Or

const set = (newVars: Partial<Vars>) => {...}

See this on TS Playground

If you only want to add ? to certain values, just intersect the partial of the optional keys and required keys.

type PickOptional<T extends Record<any, any>, Opt extends string> = Partial<Pick<T, Opt>> & Omit<T, Opt>

// or doing the inverse
type PickRequired<T extends Record<any, any>, Req extends string> = Required<Pick<T, Req>> & Omit<T, Req>

interface NewVars extends PickOptional<Vars, 'a'> {}
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