ZiiMakc
ZiiMakc

Reputation: 36966

React TS get prop for shared component

How to let typescript know about err type?

type InputProps = {
  err?: boolean
}

export const Input = forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<'input'>>(({ err, ...rest }, ref) => {
  // some use for err here
  return <StyledInput {...rest} ref={ref} />
})


const StyledInput = styled.input<InputProps>`
  box-shadow: inset 0 0 0 1px ${({ err, theme }) => (err ? theme.badColor : theme.primaryColor)};
`

Error is:

Property 'err' does not exist on type 'PropsWithChildren, HTMLInputElement>, "form" | "style" | "title" | "pattern" | "key" | "accept" | "alt" | "autoComplete" | ... 276 more ... | "onTransitionEndCapture">>'.ts(2339)

Upvotes: 1

Views: 264

Answers (2)

Damien Flury
Damien Flury

Reputation: 778

Use the InputProps-type as your second generic argument:

export const Input = forwardRef<HTMLInputElement, InputProps>(({ err, ...rest }, ref) => {
  return <StyledInput {...rest} ref={ref} />
});

Upvotes: 1

ZiiMakc
ZiiMakc

Reputation: 36966

Oh, found the answer myself, you just need to add & InputProps:

type InputProps = {
  err?: boolean
}

export const Input = forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<'input'> & InputProps>(({ err, ...rest }, ref) => {
  // some use for err here
  return <StyledInput {...rest} ref={ref} />
})


const StyledInput = styled.input<InputProps>`
  box-shadow: inset 0 0 0 1px ${({ err, theme }) => (err ? theme.badColor : theme.primaryColor)};
`

Upvotes: 1

Related Questions