Search code examples
javascriptreactjstypescriptnext.jsfrontend

Next.js next/image 'image' implicity has an 'any' type - how to fix?


I am new to Next.js and TypeScript and cant seem to find any resources on how to fix this issue:

import Image from 'next/image';

export default function Item({ image }) { // <-- parameter image needs a 'type' definition?
  ...
}

but the above gives this notice/warning/error with regard to the parameter image:

Binding element 'image' implicitly has an 'any' type.ts(7031). (parameter) image: any

Sample usage of image:

<Image src={image} alt={title} fill />

I understand that TS needs variable types to be defined/declared but I sure as heck have no idea what 'type' NextJS Image should be and I also know that giving it the any type is not the way to go either? How can I fix this issue?

I tried the following but doesn't work:

export default function Item({ image: Image }) { // <-- tried the `image: Image` syntax

Does anyone have any resource, documentation, or preferred place to search up what the right type would be for a parameter/function and the right syntax that goes along with it to quell these warnings?

Thanks in advance.


Solution

  • by default in typescript if you don't specify the type of a variable, it will be implicitly typed by element affect inside

    It if it's an object by default the implicit type will be any https://www.typescriptlang.org/docs/handbook/type-inference.html

    but you have the warning due to noImplicitAny which is true by default in tsconfig https://www.typescriptlang.org/tsconfig/#noImplicitAny

    you have to explicitly define the type of your parameter or if you truly want any specify it

    export default function Item({ image }: {image: Image}) 
    

    just be careful in your case the type affected should have image property inside it to be valid

    if Image object contain the path of the image you will have the following

    export default function Item({ image }: {image: string})