Home > OS >  Typescript: Using resizeObserver but getting type error
Typescript: Using resizeObserver but getting type error

Time:10-04

I am trying to use a resizeObserver and in TS, I am getting the following error:

Argument of type '(element: ResizeObserverEntry) => void' is not assignable to parameter of type 'ResizeObserverCallback'.
  Types of parameters 'element' and 'entries' are incompatible.
    Type 'ResizeObserverEntry[]' is missing the following properties from type 'ResizeObserverEntry': borderBoxSize, contentBoxSize, contentRect, target

my code is:

const resizeObserver = new ResizeObserver((element: ResizeObserverEntry) => {

   // do stuff
});

I have tried using ResizeObserverCallback but getting a similar error as well. I dont want to have to just revert to using any

CodePudding user response:

new ResizeObserver expects ResizeObserverCallback as a callback type:

interface ResizeObserverCallback {
    (entries: ResizeObserverEntry[], observer: ResizeObserver): void;
}

It means that first argument of a callback is an array of ResizeObserverEntry and second argument is an observer: ResizeObserver.

You don't even need to use explicit types in your callback. TS is able to contextually infer them.

const resizeObserver = new ResizeObserver((entries,observer) => { // ok

  // do stuff
});

As you might have noticed, entries and observer are typed and not any

  • Related