简体   繁体   中英

Type checking forwardRef with ...rest property in React/Typescript

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM