javascript VSCode类型脚本智能感知错误

r3i60tvu  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(123)

我一直在尝试使用SvelteKit为我的网站创建ServiceWorker,但遇到了一个问题。我创建了一个文件/src/service-worker.ts,并在其中放入了以下代码

import { build, files, prerendered, version } from '$service-worker';

const applicationCache = `applicationCache-v${version}`;
const staticCache = `staticCache-v${version}`;

const returnSSRpage = (path) =>
  caches.open("ssrCache").then((cache) => cache.match(path));

// Caches the svelte app (not the data)
self.addEventListener("install", (event) => {
  event.waitUntil(
    Promise.all([
      caches
        .open("ssrCache")
        .then((cache) => cache.addAll(["/"])),
      caches
        .open(applicationCache)
        .then((cache) => cache.addAll(build)),
      caches
        .open(staticCache)
        .then((cache) => cache.addAll(files))
    ])
      .then(self.skipWaiting()),
  )
})
... reduced code

当运行npm run build时,这段代码编译得非常好,并且代码在浏览器中运行。但是,我的VSCode智能感知有些地方出错了。最值得注意的是,它说eventwaitUntil属性不存在。Property 'waitUntil' does not exist on type 'Event'.ts(2339)以及其他一些东西,例如Property 'skipWaiting' does not exist on type 'Window & typeof globalThis'.ts(2339)Cannot find name 'clients'.ts(2304)
现在,我对Javascript和Typescript还很陌生,但是根据我的经验,Intellisense不应该输出编译过程中没有出现的错误。为什么会发生这种情况?
我不确定要提供什么信息。我的TS版本是4.7.4,这也是VSCode用于智能感知的版本。我已经安装了JS和TS的ESLint扩展。
有什么问题吗?谢谢!

vngu2lb8

vngu2lb81#

您可以将"WebWorker"添加到tsconfig.json中的compilerOptions.lib,并在service worker文件中声明self的类型:

declare var self: ServiceWorkerGlobalScope;

这将导致自动推断事件类型,而无需通过事件名称进行进一步注解。
您可能需要重新启动TS服务器(有一个命令可用于此操作:TypeScript: Restart TS Server)。
不过,奇怪的是它会这样建造...

1bqhqjot

1bqhqjot2#

这对我来说非常有效:

const sw: ServiceWorkerGlobalScope = self as unknown as ServiceWorkerGlobalScope;

现在你用sw替换self,这更有意义,而且你得到了正确的类型。

相关问题