Home > Blockchain >  How to fix: type '{ source: string; }' is not assignable to type 'string'
How to fix: type '{ source: string; }' is not assignable to type 'string'

Time:03-12

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?

CodePudding user response:

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.

CodePudding user response:

right type of the component should be

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