2

I am using the library KonvasJs for React. (https://github.com/lavrton/react-konva#using-images)

To load an image in javascript/React it is

  componentDidMount() {
    const image = new window.Image();
    image.src = "http://konvajs.github.io/assets/yoda.jpg";
    image.onload = () => {
      // setState will redraw layer
      // because "image" property is changed
      this.setState({
        image: image
      });
    };
  }

It works fine. When I switch Typescript, I have this error: enter image description here

I have tried also to add:

interface Window {
    Image: typeof Image;
}

or

  interface Windows extends Window {
      Image: typeof Image;
  }

or

declare global {
  interface Window {
      Image: typeof Image;
  }
}

Without success

enter image description here or enter image description here Any ideas?

Related issues:

https://github.com/Microsoft/TypeScript/issues/10241

TypeScript -- new Image() from global scope

https://ourcodeworld.com/articles/read/337/how-to-declare-a-new-property-on-the-window-object-with-typescript

https://www.reddit.com/r/typescript/comments/5fieja/how_do_i_add_a_property_to_window_in_typescript_2/

Alan
  • 9,167
  • 4
  • 52
  • 70

3 Answers3

2

Solution is :

const image = new (window as any).Image()
image.src = './dragFile.png'
image.onload = () => {
  this.setState({
    image: image
  })
}

source: https://github.com/Microsoft/reactxp/blob/master/src/web/Image.tsx#L139

Alan
  • 9,167
  • 4
  • 52
  • 70
0

You're probably not including the DOM library.

If you're using a tsconfig.json, include the following:

{
    "compilerOptions": {
        "lib": [
            "dom"
        ]
    }
}

Or if using the CLI:

tsc --lib dom ...

See https://www.typescriptlang.org/docs/handbook/compiler-options.html for more info.

sroes
  • 14,663
  • 1
  • 53
  • 72
  • Thanks for your answer, but I do include the dom and it is still not working: "lib": ["es6", "dom"], – Alan Jun 06 '18 at 10:08
0

I found a solution using the following Stackoverflow question

Since you're using KonvajS, they override the global Image definition with their own type which breaks the default Image HTMLImageElement DOM type

If you're using stricter tslint rules that don't allow any keyword then this solution would work:

interface IHTMLImageElement {
  prototype: HTMLImageElement
  new(): HTMLImageElement
}

declare global {
  // tslint:disable-next-line
  interface Window {
    Image: IHTMLImageElement
  }
}
Guy
  • 2,883
  • 1
  • 32
  • 39