[英]Type checking forwardRef with ...rest property in React/Typescript
I'm struggling to get type checking in Typescript to work for a React component which uses forwardRef and has a ...rest property.我正在努力让 Typescript 中的类型检查适用于使用 forwardRef 并具有 ...rest 属性的 React 组件。
Example:例子:
import React from 'react'
interface InputWithLabelProps {
label: string,
[rest: string]: unknown,
}
const InputWithLabel = React.forwardRef<HTMLInputElement, InputWithLabelProps>(
({ label, ...rest }, ref) => (
<>
<label htmlFor="field">{label}</label>
<input id="field" ref={ref} {...rest} />
</>
),
)
export default InputWithLabel
This will give component the following signature:这将为组件提供以下签名:
(alias) const InputWithLabel: React.ForwardRefExoticComponent<Pick<InputWithLabelProps, keyof InputWithLabelProps> & React.RefAttributes<HTMLInputElement>>
import InputWithLabel
This will not give correct type checking for example it's not necessary to provide label property which should be required.这不会给出正确的类型检查,例如不需要提供应该需要的标签属性。 If I remove either forwardRef or the ...rest property it works, but that is not an option.
如果我删除 forwardRef 或 ...rest 属性,它可以工作,但这不是一个选项。
How can I use forwardRef on a component which has ...rest property and at the same time have type checking?如何在具有 ...rest 属性并同时进行类型检查的组件上使用 forwardRef?
Using [rest: string]: unknown
you allow any string property to be passed to your input element which (for a reason I do not understand why) renders your other prop types useless.使用
[rest: string]: unknown
您允许将任何字符串属性传递给您的输入元素,这(出于某种原因我不明白为什么)会使您的其他道具类型无用。 Assuming you want to type your component with a mandatory label
and otherwise any props belonging to an <input>
-element, you can extend this by using either:假设您要使用强制
label
键入组件,否则任何属于<input>
元素的道具,您可以使用以下任一方法扩展它:
interface InputWithLabelProps extends React.InputHTMLAttributes<HTMLInputElement> {
label: string
}
or combining the types using:或使用以下组合类型:
type InputWithLabelProps = {
label: string
} & React.HTMLProps<HTMLInputElement>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.