Reputation: 3969
I wrote a new component like the following code:
function CustomInput({ floatLabel, ...props }: any) {
return (
<label>
{floatLabel}
<input {...props} />
</label>
);
}
I want to provide Typescript IntelliSense for this element (An HTML input + new floatLabel
attribute )
<CustomInput floatLabel="x" type="input" /> // I need full IntelliSense for this element.
Just like other standard HTML tags.
How to provide full IntelliSense by extending TS Types as a standard HTML input with a new floatLabel
attribute for <CustomInput>
?
Upvotes: 0
Views: 2366
Reputation: 6837
The problem is { floatLabel, ...props }: any
. You have to provide type information for the props to the CustomInput
component.
To get the type information for props of input element as well, you need to add React.HTMLProps<HTMLInputElement>
in the declaration for the CustomInput
component.
interface ICustomInputProps {
floatLabel: string; // the type for value of floatLabel
// you also have to define type information for other props
}
// To get type info for input props
type TExtendedProps = ICustomInputProps & React.HTMLProps<HTMLInputElement>
function CustomInput({ floatLabel, ...props }: TExtendedProps) {
return (
<label>
{floatLabel}
<input {...props} />
</label>
);
}
If you want to use React.FC
generic
interface ICustomInputProps {
floatLabel: string; // the type for value of floatLabel
// you also have to define type information for other props
}
// To get type info for input props
type TExtendedProps = ICustomInputProps & React.HTMLProps<HTMLInputElement>
const CustomInput: React.FC<TExtendedProps> = ({ floatLabel, ...props } => {
return (
<label>
{floatLabel}
<input {...props} />
</label>
);
}
Upvotes: 2