Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading