In some cases the typescript compiler doesn’t detect the types correct which requires me to be redundant. In my head this types are absolutly safe declared. Do I miss something or is the compiler incorrect? And is there any way I can help him autodetect the types correct without repeating myself?
interface Dto {
value1: boolean;
value2: string;
value3: string;
}
class Model {
firstValue!: boolean;
secondValue!: number;
thirdValue!: string;
parse<
dtoName extends keyof Dto,
>(entry: dtoName, raw: Dto[dtoName]): void {
switch(entry) {
case 'value1':
/* raw is save a boolean isn't it? Its declared as …
Dto[dtoName]
= Dto['value1']
= boolean
*/
this.firstValue = raw;
break;
case 'value2':
this.secondValue = Number(raw);
break;
case 'value3':
this.thirdValue = raw; // same here
break;
default:
throw new Error(`Unknown entry ${entry}`);
}
}
}
Link to Playground