0

This has to be a simple fix, but I can't find anything explaining how you resolve this issue. I'm using Next.js and Typescript to make a component display an image and use hooks to modify said image. The problem is, when I pass in a string to the parameter that is typed as string, I get this error: Type '{ source: string; }' is not assignable to type 'string'.ts(2322)

Given this component:

const ImageToggleOnMouseOver = (source: string) : JSX.Element => { ... }

When I try to use it, like so, I get the above error:

return (
  <div>
    <ImageToggleOnMouseOver source='/heads_up.jpg' />
  </div>
);

When provided as source: any it works fine, but shouldn't string also work since I'm expecting to pass in a string after all?

2
  • This answer explains how JSX props work (excluding the irrelevant details of React internals) Commented Mar 11, 2022 at 17:46
  • I think you just have to write either (props) (the param name should not matter) which are of type any and use props.source or use ({source: string}) instead Commented Mar 11, 2022 at 17:48

2 Answers 2

1

You need to change the declaration in the component. It is trying to assign the props object of { source: string } to a parameter declared as (source: string). You need to change the function definition to this:

const ImageToggleOnMouseOver = ({source}: {source: string}) : JSX.Element => { ... }

By unpacking the props object and retrieving the source prop, you are able to specify the properties that you need in the function, and you are specifying the type of props.

Sign up to request clarification or add additional context in comments.

Comments

1

right type of the component should be

const ImageToggleOnMouseOver = ({source} :{source: string}) : JSX.Element => { ... }

1 Comment

Could you explain more on why that is, please?

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.