使用正确的泛型迭代对象
Iterate over object with correct generic type
我想迭代通用接口。并在jsx中使用对象的值。但是打字稿抛出以下内容:
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>
);
}
如何定义接口和组件才能正确输入?
<input />
期望 value
为 string | number | readonly string[] | undefined
。
我们可以这样获取有效的input.value
类型:
type InputValue = React.InputHTMLAttributes<HTMLInputElement>['value']
现在我们只需要对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>
);
}
应该可以。
我想迭代通用接口。并在jsx中使用对象的值。但是打字稿抛出以下内容:
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>
);
}
如何定义接口和组件才能正确输入?
<input />
期望 value
为 string | number | readonly string[] | undefined
。
我们可以这样获取有效的input.value
类型:
type InputValue = React.InputHTMLAttributes<HTMLInputElement>['value']
现在我们只需要对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>
);
}
应该可以。