I am working on coding a react input component that accepts a defaultValue
parameter of type string | number
. This component has a state type matching the type of the received defaultValue
;
This is my code:
type TypeName<T> = T extends number ? "number" : "string";
interface IInputProps<P extends string | number>{
defaultValue: P,
rule: (value: P)=>boolean,
onChange: (value: P)=>void
}
interface IInputState<P extends string | number>{
value: P,
type: TypeName<P>
}
class Input<P extends string | number> extends Component<IInputProps<P>,IInputState<P>>{
constructor(props:IInputProps<P>){
super(props);
this.state = {
type: typeof props.defaultValue,
value: this.props.defaultValue
}
An error is occurring in the constructor section
ERROR in [at-loader] ./src/components/Input/index.tsx:21:4
TS2322: Type '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' is not assignable to type 'TypeName<P>'.
Type '"string"' is not assignable to type 'TypeName<P>'.
Any suggestions on how to resolve this issue?