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

163
Visualizações
why type protected is failed in typescript

I have faced one issue, see this link in typescript platform https://www.typescriptlang.org/play?ts=4.2.3#code/C4TwDgpgBA0hIGcoF4oHICGaoB90CNs80BjNAbgChRIoBJANRSgG9KooBtAa3igEsAdrHgIAugH4AXFEEBXALb4IAJyoBfSiQA2GBEgCqCVa3ZQwK-gDcMwaDe1yICGY2Yt1VMxgAmPgMIA9nKCwAAUvCAycIgANFAkwaEy8kqqAJSmHBz8AGZQYTQQgfnAABb8CAB0Dk4IPPBiKMioaKnKKmiZbNnZ5ZU1GI7ODSBNqP3VtSORTQDUUACMVL2aHJrqQA;

I don't understand why typeof in this scene can't infer 'this.values[key]' type correctly;

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

0

This happen because you defined values as empty object without keys. So error make sense: this.values[key] is undefined when you trying to access to.

All you need is add check if object property exist and set default value if not:

type Keys = 'a' | 'b' | 'c';
type IV = {
  [key in Keys]?: number;
}
class User {
  private values: IV = {};

  addCount(key: Keys, count: number) {
    if (typeof this.values[key] === 'number') {
      this.values[key] = (this.values[key] || 0) + 1;
    }
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I think type Keys = 'a' | 'b' | 'c'; the first line is wrong. here you should provide a data type not a value.

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