0

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. enter image description here

How to provide full IntelliSense by extending TS Types as a standard HTML input with a new floatLabel attribute for <CustomInput>?

enter image description here

1 Answer 1

2

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>
  );
}

3
  • what about HTMLInput attributes? I want CustomInput has all HTMLInput attributes too. With your code type, name & ... are not valid. I don't want to define everything! I want to be HTMLInput + a new floatLabel attribute.
    – HamedFathi
    Commented Jun 3, 2020 at 19:13
  • We should change the ICustomInputProps definition to interface ICustomInputProps extends React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> { floatLabel: string; }
    – HamedFathi
    Commented Jun 3, 2020 at 19:24
  • There is another way, which is more readable. updated the answer have a look. :) Commented Jun 3, 2020 at 19:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.