Home > Enterprise >  How to FIx this error TS2349: This expression is not callable
How to FIx this error TS2349: This expression is not callable

Time:10-01

Code in typescript

window.addEventListener('message', (event) => {
    event.source.postMessage("response",event.origin)
});

get Error at "event.origin"

 TS2349: This expression is not callable.
  Each member of the union type '((message: any, targetOrigin: string, transfer?: Transferable[]) => void) | { (message: any, transfer: Transferable[]): void; (message: any, options?: PostMessageOptions): void; } | { ...; }' has signatures, but none of those signatures are compatible with each other.

Thank in advance

CodePudding user response:

I can't see the specific error you've mentioned in that code in the playground, but I do see two errors, so:

  1. event.source can be null, but your code assumes it isn't null. You have to handle that, because you can't do null.postMessage(/*...*/).

  2. event.origin is a string, but event.source on a MessageEvent (when it's not null) isn't necessarily a window object, so you can't assume the second parameter on postMessage allows a string. Sadly, postMessage on different objects has differing parameter lists. Window's postMessage accepts a string as the second argument, but (for instance) MessagePort's doesn't.

I'm going to assume since you're trying to pass a string to it, you expect event.source to be a window. If so, you can solve both problems with a since type guard:

window.addEventListener('message', (event) => {
    if (event.source instanceof Window) {
        event.source.postMessage("response", event.origin);
    }
});

Playground link

null never passes an instanceof check, so that handles both cases.

  • Related