import React from "react";
type FormFieldProps<T> = {
value: T;
onChange: (value: T) => void;
};
function FormField<T>({ value, onChange }: FormFieldProps<T>) {
return (
<input
type="text"
value={String(value)}
onChange={(e) => onChange(e.target.value as unknown as T)}
/>
);
}
// Usage
const App = () => {
const [name, setName] = React.useState<string>("");
const [age, setAge] = React.useState<number>(0);
return (
<div>
<FormField value={name} onChange={setName} />
<FormField value={age} onChange={setAge} />
</div>
);
};
export default App;
To ensure that our FormField
component only works with certain types, we can add type constraints.