HamedFathi
HamedFathi

Reputation: 3969

How to extend JSX types for Typescript?

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

Upvotes: 0

Views: 2366

Answers (1)

subashMahapatra
subashMahapatra

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

Related Questions