Home > Mobile >  Type checking forwardRef with ...rest property in React/Typescript
Type checking forwardRef with ...rest property in React/Typescript

Time:06-23

I'm struggling to get type checking in Typescript to work for a React component which uses forwardRef and has a ...rest property.

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.

How can I use forwardRef on a component which has ...rest property and at the same time have type checking?

CodePudding user response:

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. 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:

interface InputWithLabelProps extends React.InputHTMLAttributes<HTMLInputElement> {
  label: string
}

or combining the types using:

type InputWithLabelProps = {
    label: string
} & React.HTMLProps<HTMLInputElement>
  • Related