Home > OS >  How to resolve "The 'this' context of type 'void' is not assignable to meth
How to resolve "The 'this' context of type 'void' is not assignable to meth

Time:05-01

I'm trying to wrap a native element with a custom component, and I want to make sure if a onload callback is supplied that it gets called.

The trouble is I'm getting a typescript error when I try and invoke the function.

The 'this' context of type 'void' is not assignable to method's 'this' of type 'never'.

What am I doing wrong / how do I appease typescript?

export const LoadAwareImage = ({ onl oad, className, alt, ...props }: ComponentPropsWithoutRef<"img">) => {
  const [loaded, setLoaded] = useState(false);

  return (
    <img
      onl oad={(e) => {
        setLoaded(true);
        onl oad && onl oad(e); // The 'this' context of type 'void' is not assignable to method's 'this' of type 'never'.
      }}
      alt={alt}
      className={clsx(loaded && "loaded", className)}
      {...props}
    />
  )
}

CodePudding user response:

Change

 onl oad && onl oad(e);

to

onLoad && onl oad.call(this, e);

closed issue on typescript git for reference

CodePudding user response:

I don't recommend you use && for a general if statement.

This is more clear and will always be more clear for anyone reading the code, and as a bonus it fixes your issue:

export const LoadAwareImage = ({ onl oad, className, alt, ...props }: ComponentPropsWithoutRef<"img">) => {
  const [loaded, setLoaded] = useState(false);

  return (
    <img
      onl oad={(e) => {
        setLoaded(true);
        if (onLoad) onl oad(e);
      }}
      alt={alt}
      className={clsx(loaded && "loaded", className)}
      {...props}
    />
  )
}
  • Related