12

I want to get some info from an image that i load using new image() with typescript. I try this code:

width;
heigth;
init(){
    let image = new Image();
    image.src = "url";

    image.onload((event) => {
    this.width = event.width;
    this.heigth = event.heigth;
    })
}

But i get this error:

void' is not assignable to parameter of type 'Event'. Property 'bubbles' is missing in type '() => void'

I search examples on how to use this event but i can't find anything.

4 Answers 4

13

You are trying to call onload rather than assign an event handler. Here is a quick fix for you...

image.onload = (event) => {
  // ...
};

You will also find that the general Event type doesn't have width and height, so you may need to specialise the type for that too.

interface SizedEvent {
  width: number;
  height: number;
}

function isSizedEvent(e: any): e is SizedEvent {
  return (e && e.width !== undefined && e.height !== undefined);
}  

image.onload = (event) => {
  if (isSizedEvent(event)) {
    // event.width is now available
  }
};
Sign up to request clarification or add additional context in comments.

Comments

2

HTMLImageElement worked for me:

  image.onload = function (this: HTMLImageElement) {
  const height = this.height;
  const width = this.width;
  console.log('Image size ', [width, height])
};

1 Comment

What a neat solution!
1

In Angular 14.1, I was also able to simply cast to HTMLImageElement...


    var image = new Image();
    image.onload = (onLoadResult) => {
    const img = onLoadResult.target as HTMLImageElement;
    // do cool stuff
    }
    image.src = screenShotDataUrl;

Comments

0

This worked for me:

img.onload = function () {
    const { width, height } = this as GlobalEventHandlers & {
        width: number
        height: number
    }
}

Comments

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.