问题
I have a web worker that I want to write with TypeScript.
The problem is Worker.postMessage - TypeScript assumes that every script will be loaded in the window context, and so expects Window.postMessage, which has a different syntax.
This means TypeScript throws an error when I try to use postMessage
.
There are ways to work around this, for instance by redefining the function declare function postMessage(message: any)
, but most of these are ugly kludges at best - the whole point of TS is checking types, declaring my own dummy ones defeats that.
By the same token - window
(and everything in it's context) is not available in this context and should be picked up as an error by TS. For instance alert('message')
should result in a TS warning, not a run time bug.
Is there any way to do it where the file can pick up the actual definition (from webworker.es2016.d.ts
) and somehow tell TypeScript that this code will be running in the worker context instead of the window?
回答1:
If you check the compiler options you will see that there is a webworker option for --lib
. The problem is that you can't compile regular code and code for web worker at the same time. You can put your web worker code in a separate folder with it's own tsconfig.json
and copule it separately:
"compilerOptions" : {
"target": "es2015",
"lib": [
"es2015"
"webworker"
]
}
Or you can invoke the compiler explicitly for the webworker code:
tsc .\sample.ts -lib es2015,webworker
来源:https://stackoverflow.com/questions/48950248/how-do-i-strongly-type-a-typescript-web-worker-file-with-postmessage