I have a <InputField>
component in my app with the following type definition for the props:
interface InputFieldProps extends React.HTMLAttributes<HTMLInputElement> {
customProp: string;
}
My component looks like this:
const InputField: React.FC<InputFieldProps> = ({ customProp, ...htmlProps }) => {
return (
<input {...htmlProps} />
);
};
I would expect that I can now pass the prop disabled
or required
to that component, as these properties are part of the HTMLInputElement type definition. However, I get the error:
Property 'disabled' does not exist on type 'IntrinsicAttributes & Props'
I tried passing disabled as disabled={true}
as well as just disabled
with no success. I can, however, pass placeholder
as a prop. So some properties in the HTMLInputElement type definition seem to work, while others don't.
CodePudding user response:
The error message Property '...' does not exist on type 'IntrinsicAttributes & Props' suggests that the ...htmlProps spread operator is spreading the wrong type of object. This can happen if the htmlProps object has a different type than the expected InputFieldProps type.
In your case, the InputFieldProps type extends the React.HTMLAttributes type, which includes the disabled and required properties. However, if the htmlProps object has a different type, it will not include these properties.
To fix this, you can ensure that the htmlProps object has the correct type by using the React.InputHTMLAttributes type. This type is similar to the React.HTMLAttributes type, but it is specifically for the input element, and it includes all the possible input element attributes.
Here is an example of how your code could look like with this change:
import React from 'react';
interface InputFieldProps extends React.InputHTMLAttributes<HTMLInputElement> {
customProp: string;
}
const InputField: React.FC<InputFieldProps> = ({ customProp, ...htmlProps }) => {
return (
<input {...htmlProps} />
);
};
With this change, you should be able to pass the disabled and required properties to your InputField component, and they will be spread correctly to the input element.
CodePudding user response:
Using HTMLProps<HTMLInputElement>
instead of HTMLAttributes<HTMLInputElement>
would work:
interface InputFieldProps extends React.HTMLProps<HTMLInputElement> {
customProp: string;
}
<InputField customProp="foo" disabled required />