I have a problem and I found the fix but I want to know the why it’s not working as I wanted before, because it seems that it should.
interface InvestmentInput {
initialInvestment: number;
annualInvestment: number;
expectedReturn: number;
duration: number;
}
function handleChange(inputIdentifier: keyof InvestmentInput, value: string) {
setUserInput(prevUserInput => {
return {
...prevUserInput,
[inputIdentifier]: value,
};
});
}
In that snippet above, the line [inputIdentifier]: value
doesn’t throw any error related to typing, shouldn’t it? I was able to correctly type that with this:
[inputIdentifier]: +value as typeof prevUserInput[keyof InvestmentInput]
But yet, why I didn’t get any error by before? Since inputIdentifier
is keyof InvestmentInput
, and the prevUserInput
is of type InvestmentInput
.
Also another work around was the following (my final code now):
function handleChange(inputIdentifier: keyof InvestmentInput, value: string) {
setUserInput(prevUserInput => {
const updatedUserInput = { ...prevUserInput } as InvestmentInput;
updatedUserInput[inputIdentifier] = +value;
return updatedUserInput;
});
}
With that if I remove the plus sign it’ll complain about the type of value.
It’s working but the initial approach is more concise, is it possible to make that work? If it isn’t, why?
PS.: Should the return value of setUserInput
be implicitly of type InvestmentInput
?
Thanks!