I hope someone can help with this. I'm pretty new to the typescript react world and i wrote a Textarea child component which takes a function as an onChange prop. This function then gets called with 2 strings as arguments from the child component.
In the parent component i know more specifically what the second argument of that function call should look like (keyof Type). The problem is, that typescript tells me that type string is not assignable to type [insert strings of keys of Type].
I think it's supposed to be solved by using generics? but I simply can't wrap my head around it.
I tried this how can you express "keyof T" to be a subset of String? but the error wouldn't go away.
Barebones Code can be found here: https://codesandbox.io/s/modest-dhawan-v3z2y In this example the first and third Textarea should not throw any errors, since the second argument will be a key out of the specified type. The
How can I solve this?
I would like both Textarea Components in the index.tsx to not throw any type errors, once again I think generics might be the solution but I can't figure it out.
Thanks is advance.
There is no need for generics nor a second argument. As you are passing down the value of that argument as props, it suggests that you already know what the value is going to be in the parent component. You can either pass a lambda or a bound function with the name already set.
<TextArea
id="ErrorDescription"
name="ErrorDescription"
className="form-control"
isRequired
value={inputValues.ErrorDescription}
onChange={(value) => updateValue(value, 'ErrorDescription')}
/>
Or
// Note I had to swap the order of parameters to facilitate binding
const updateValue = (eventtargetname: keyof InputValues, eventvalue: string) => ...
const updateErrorValue = updateValue.bind(this, 'ErrorDescription')
return (
...
<TextArea
id="ErrorDescription"
name="ErrorDescription"
className="form-control"
isRequired
value={inputValues.ErrorDescription}
onChange={updateErrorValue}
/>
)
Personally, I'd go with lambdas as they are a lot cleaner. Bound functions perform better in class components when used outside the render function but that is no longer possible with the functions & hooks paradigm.
Working example. https://codesandbox.io/s/quizzical-darkness-79eux
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With