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

160
Visualizações
How can I fill up missing object parameters in an elegant way?

I am having trouble using initial parameters (I am not sure if there is a typescript solution or it is just a JavaScript question, so I present you the Javascript equivalent to you):

const helloWorldWithOptions = (options = { a:1, b:2 } ) => {
  console.log("Hello World!")
};

When using the function:

helloWorldWithOptions( {a:4} );

Typescript says that I am missing the object key b when using the function. What I would expect is that js/ts filling up the missing values with the initial parameters. If there is already a state of the art, let me know.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can specify default values whenever you declare a function:

function aFunction({a = 1, b = 2}) {console.log(a, b)}

aFunction({}) //prints "1 2"

in this case, 'aFunction' receives an object, and whenever you call the function with an empty object, it automatically fills the blank fields. Alternatively, you can call 'aFunction' with the parameters you want, for example:

aFunction({a: 2, b: 3}) //prints "2 3"
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the Partial type and ... spreading to combine your defaults with the caller's overrides.

TS playground

const defaults = { a: 1, b: 2 };

// Could use a named type instead of `typeof defaults` too.
const helloWorldWithOptions = (options: Partial<typeof defaults> = {}) => {
  const mergedOptions = { ...defaults, ...options };
  console.log(mergedOptions);
};
helloWorldWithOptions({ a: 3 });

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