Eliya Cohen
Eliya Cohen

Reputation: 11518

Typescript - How can I extend an interface with an existing property?

I'm building a UI system via React using Typescript. I want to create an <Input /> component that composes a real <input />. The component <Input /> should accept as a prop every attribute that is accepted by the <input />.

In order to do so, I checked what <input /> in React accepts, and that was the result:

React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>;

At first, I set my interface like so:

interface InputProps extends React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>;

but it's too long to be understandable. So I thought about using Pick:

interface InputProps extends Pick<JSX.IntrinsicElements, 'input'>`

but it just adds to the interface the input property itself, instead of actually extend it:

interface Props extends ...  {}

const Input = (props: Props) => {
    return <input {...props} />
}

Upvotes: 3

Views: 3182

Answers (1)

Chris
Chris

Reputation: 2427

interface for native input is HTMLInputElement

interface InputProps extends HTMLInputElement {}

interface with React props

import { InputHTMLAttributes } from "react";

interface InputProps extends InputHTMLAttributes<HTMLInputElement>

to access the ref use Forwarding Ref:

const MyInput = React.forwardRef((props, ref) => {
  return(<input {...props} ref={ref} />);
});

Upvotes: 7

Related Questions