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

125
Visualizações
Use keyof on optional field

I would like to use keyof to describe the parameters of a function, based on an optional field in a Object. And I would like to add a default value.

interface foo {
  bar?: {
     opt1: string,
     opt2: string
  }
}

function func(option: keyof foo["bar"] = "opt1") ...

But as bar is optional i got Type 'string' is not assignable to type 'never'

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

0

You can get rid of the possibility of undefined by using NonNullable:

function func(option: keyof NonNullable<foo["bar"]> = "opt1")

Note that the above will also get rid of the possibility of null, which may or may not be desired. Another option is you could use Exclude, which is more verbose but gives you more flexibility:

function func(option: keyof Exclude<foo["bar"], undefined> = "opt1")

For more info on these utility types, see this page: https://www.typescriptlang.org/docs/handbook/utility-types.html

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