2

When I first started to adapt typescript in react, I notice I can't using ...props, as typescript check every single prop that are passed in the components. It's great but it's also annoying, where I have to pass native props like id, name etc declaratively as props.


interface MyComponentProps {
  name: string,
  id: string,
  placeholder: string
}

const MyComponent = ({
  name,
  id,
  placeholder
}: MyComponentProps) => {
  return <input type="text" placeholder={placeholder} name={name} id={id}/>
}
export default function App() {
  return (
    <div className="App">
      <MyComponent placeholder="Name" name="something" id="myInput" />
    </div>
  );
}

2 Answers 2

4

You should edit your interface such that it is extending the props of the HTML input element:

interface MyComponentProps extends InputHTMLAttributes< HTMLInputElement>)  {
  // add other custom props
}

const MyComponent: React.FC<MyComponentProps> = (props) => (...)
Sign up to request clarification or add additional context in comments.

3 Comments

besides InputHTMLAttributes what other type are there? for div, li etc, how do I know those thing?
You can refer to this cheatsheet! saltycrane.com/cheat-sheets/typescript/react/latest its not that complicated once you get a hang of it
This was crazy helpful to me and I'm annoyed that you were downvoted. To future readers, I needed this for an anchor "a" link and I used LinkHTMLAttributes instead of InputHTMLAttributes. In my editor I just navigate to the file where the types are defined and they're all there with the supported attributes.
0

You can explicitly cast it to HTMLAttributes

Declare an interface like union of component's props with HTMLAttributes

interface MyComponentProps = {}

const MyComponent: React.FC<MyComponentProps & HTMLAttributes>...

Detailed explanation you can find here: https://stackoverflow.com/a/40032869/4186110

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.