Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda