CodexBloom - Programming Q&A Platform

TypeScript generics and default type parameters causing advanced patterns in a React component

👀 Views: 15 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
typescript react generics TypeScript

I'm not sure how to approach I'm confused about I'm stuck on something that should probably be simple. I'm currently working with an scenario with TypeScript generics in a React component where I'm trying to create a reusable form input component. I defined the component with a generic type `T`, and I want to set a default type for that generic. However, when I pass different types to the component, it seems to maintain the default type instead of inferring the correct type from the props. Here's what I've tried: ```typescript interface InputProps<T = string> { value: T; onChange: (value: T) => void; } const Input = <T,>({ value, onChange }: InputProps<T>) => { return <input value={value as string} onChange={(e) => onChange(e.target.value as unknown as T)} />; }; ``` When using the component, I do this: ```typescript const App = () => { const [name, setName] = useState<string>(''); return <Input value={name} onChange={setName} />; }; ``` However, if I try to use the input for a different type, such as a number: ```typescript const AppNumber = () => { const [age, setAge] = useState<number>(0); return <Input value={age} onChange={setAge} />; }; ``` I get the following behavior: ``` Argument of type 'number' is not assignable to parameter of type 'string'. ``` It seems like TypeScript is not inferring the type correctly from the passed props. I also tried various patterns using conditional types and default type parameters but still encountered issues. What am I doing wrong, and how can I ensure that the generic type is inferred properly based on the props passed to the component? Is there a better pattern for this scenario? My TypeScript version is 4.5.4, and I'm using React 17.0.2. My development environment is Windows. What's the best practice here? I'd really appreciate any guidance on this.