Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!