I have faced one issue, see this link in typescript platform https://www.typescriptlang.org/play?ts=4.2.3#code/C4TwDgpgBA0hIGcoF4oHICGaoB90CNs80BjNAbgChRIoBJANRSgG9KooBtAa3igEsAdrHgIAugH4AXFEEBXALb4IAJyoBfSiQA2GBEgCqCVa3ZQwK-gDcMwaDe1yICGY2Yt1VMxgAmPgMIA9nKCwAAUvCAycIgANFAkwaEy8kqqAJSmHBz8AGZQYTQQgfnAABb8CAB0Dk4IPPBiKMioaKnKKmiZbNnZ5ZU1GI7ODSBNqP3VtSORTQDUUACMVL2aHJrqQA ;
No entiendo por qué typeof en esta escena no puede inferir el tipo 'this.values[key]' correctamente;
Esto sucede porque definió values como objetos vacíos sin claves. Entonces, el error tiene sentido: this.values[key] no está undefined cuando intenta acceder a.
Todo lo que necesita es agregar verificar si existe la propiedad del objeto y establecer el valor predeterminado si no:
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; } } }Creo que type Keys = 'a' | 'b' | 'c'; la primera línea está mal. aquí debe proporcionar un tipo de datos, no un valor.