Reputation: 131
I want to iterate over a generic interface. And use the value of the object in jsx. But Typescript throws the following:
Argument of type '(key: K) => JSX.Element' is not assignable to parameter of type '(value: string, index: number, array: string[]) => Element'.
interface Props<T> {
object: T;
}
export default function BasicInputs<T, K extends keyof T>({
object,
}: Props<T>): ReactElement {
return (
<div>
{Object.keys(object).map((key: K) => (
<div>
<div className="">
<input
value={object[key]}
type="text"
name="name"
id="name"
/>
</div>
</div>
))}
</div>
);
}
How should I define the interface and component for correct typing?
Upvotes: 1
Views: 646
Reputation: 33051
<input />
expects value
to be string | number | readonly string[] | undefined
.
We can obtain valid input.value
type in this way:
type InputValue = React.InputHTMLAttributes<HTMLInputElement>['value']
Now we need just to apply appropriate restriction to T
:
type InputValue = React.InputHTMLAttributes<HTMLInputElement>['value']
type HashMap = Record<PropertyKey, InputValue>
interface Props<T> {
object: T;
}
export default function BasicInputs<T extends HashMap>({
object,
}: Props<T>) {
return (
<div>
{Object.keys(object).map((key) => (
<div>
<div className="">
<input
value={object[key]}
type="text"
name="name"
id="name"
/>
</div>
</div>
))}
</div>
);
}
It should work.
Upvotes: 1