本文介绍了如何使用 postMessage 强输入 TypeScript Web Worker 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络工作者,我想用 TypeScript 编写.

I have a web worker that I want to write with TypeScript.

问题是Worker.postMessage - TypeScript 假设每个脚本都将在窗口上下文中加载,因此需要 Window.postMessage,具有不同的语法.

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.

这意味着当我尝试使用 postMessage 时,TypeScript 会抛出错误.

This means TypeScript throws an error when I try to use postMessage.

有一些方法可以解决这个问题,例如通过重新定义函数 declare function postMessage(message: any),但其中大部分充其量只是丑陋的杂物 - TS 的重点是检查类型,声明我自己的 dummy 会打败它.

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.

出于同样的原因 - window(及其上下文中的所有内容)在此上下文中不可用,TS 应将其视为错误.例如 alert('message') 应该导致 TS 警告,而不是运行时错误.

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.

有什么办法可以让文件获取实际定义(来自 webworker.es2016.d.ts)并以某种方式告诉 TypeScript 这段代码将在工作上下文中运行而不是窗户?

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?

推荐答案

如果你检查了 编译器选项 你会看到 --lib 有一个 webworker 选项.问题是你不能同时为 web worker 编译常规代码和代码.您可以将您的网络工作者代码放在一个单独的文件夹中,并使用它自己的 tsconfig.json 并将其分开:

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"
    ]
}

或者您可以为 webworker 代码显式调用编译器:

Or you can invoke the compiler explicitly for the webworker code:

tsc .\sample.ts -lib es2015,webworker

这篇关于如何使用 postMessage 强输入 TypeScript Web Worker 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 20:58