How can I adjust the onValueChange function in a way that TypeScript recognizes that when field === 'age'
, val
will be of type number? Is there a method to do this without resorting to using 'as number'?
interface IRow {
age: number;
name: string;
born: Date;
isGood: boolean;
}
const state: IRow = {
age: 5,
name: 'bob',
born: new Date(),
isGood: true
}
const onValueChange = (field: keyof IRow) => (val: IRow[keyof IRow]) => {
if (field === 'age') {
const someNumber = 2 * val; // The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
state[field] = val; // Type 'string | number | boolean | Date' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'
}
}
onValueChange('age')(5);