Search code examples
typescriptkonvajsreact-konva

React Konva's `use-image` library throws TypeScript error


The complete error is:

TS2322: Type '[HTMLImageElement | undefined, "loaded" | "loading" | "failed"]' is not assignable to type 'HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas | undefined'. Type '[HTMLImageElement | undefined, "loaded" | "loading" | "failed"]' is not assignable to type 'OffscreenCanvas'.

I'm trying to use https://github.com/konvajs/use-image like:

const win = {
  width: window.innerWidth,
  height: window.innerHeight,
}

const App = () => {
  const image = useImage('https://konvajs.org/assets/lion.png')

  return (
    <Stage width={win.width} height={win.height}>
      <Layer>
        <Image image={image} />
      </Layer>
    </Stage>
  )
}

I tried making a declaration.d.ts file like:

declare module 'use-image' {
  function useImage(
    url: string,
    crossOrigin?: string
  ): [
    (
      | HTMLImageElement
      | SVGImageElement
      | HTMLVideoElement
      | HTMLCanvasElement
      | ImageBitmap
      | OffscreenCanvas
      | undefined
    ),
    'loaded' | 'loading' | 'failed'
  ]

  export default useImage
}

but it doesn't work either. How do I solve this issue?


Solution

  • This was a stupid mistake on my part. It should've been [image] instead of image:

    const [image] = useImage('https://konvajs.org/assets/lion.png')