Looking to create a custom React Input component using Typescript for MobX that requires the following input props:
- a mobx store
stateObject
- a key from that store
stateKey
I want Typescript to ensure that stateObject[stateKey]
is specifically of type string. This is what the ExtraProps should handle in the given example.
Unfortunately, I'm facing issues with the types not compiling as expected and receiving the error message:
TS2322: Type 'string' is not assignable to type 'K extends K ? string : any'.
Feel free to check out my related SO post here
Here is how I've approached it:
import React, {ChangeEvent, Component, InputHTMLAttributes} from "react";
type ExtraProps<T extends string | number | symbol, K extends T> = {
stateKey: K,
stateObject: { [k in T]: k extends K ? string : any }
}
type InputProps = Omit<InputHTMLAttributes<HTMLInputElement>, "value" | "onChange">
type InputPropType<T extends string | number | symbol, K extends T> = InputProps & ExtraProps<T, K>
export class InputField<T extends string | number | symbol, K extends T> extends Component<InputPropType<T, K>, any> {
constructor(props: InputPropType<T, K>) {
super(props);
this.onChange = this.onChange.bind(this)
}
onChange(event: ChangeEvent<HTMLInputElement>) {
let val: K extends K ? string : any = event.target.value; // TS2322: Type 'string' is not assignable to type 'K extends K ? string : any'.
this.props.stateObject[this.props.stateKey] = val;
}
render() {
let {stateKey, stateObject, ...props} = this.props;
return <input {...props} value={stateObject[stateKey]} onChange={this.onChange}/>
}
}
My questions would be:
- what could be causing the issue with my types?
- Is there a more efficient way to achieve my objective rather than the current approach?
Ultimately, I'm aiming for a controlled input component that seamlessly interacts with the mobx store for data management.