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;
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;
}
}
}
I think type Keys = 'a' | 'b' | 'c'; the first line is wrong.
here you should provide a data type not a value.