首页 > 解决方案 > IDE 承认变量存在,但 Typescript 给出编译器错误

问题描述

Visual Studio 代码为我的 typescript 代码提供代码完成,并且不会给出警告/错误,但是当从命令行使用 编译它时tsc fullscreen.ts,TypeScript 会给出错误消息

我的代码:fullscreen.ts

function checkFullscreen() {
    if (document.fullscreenElement !== null) {
        console.log("There is a fullscreen element");
    }
    else {
        console.log("There is no fullscreen element");
    }
}

编译器错误:

fullscreen.ts:2:18 - error TS2339: Property 'fullscreenElement' does not exist on type 'Document'.

这是我在/usr/share/code-oss/resources/app/extensions/node_modules/typescript/lib/lib.dom.d.ts使用 VS Code 的 go to definition时发现的

interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent {
...
    readonly fullscreenElement: Element | null;
...
}

其中省略号代表不相关的代码行。显然存在 TypeScript 接口来检查我的代码,但由于某种原因,TypeScript 编译器找不到它们。

对于上下文,这是我正在尝试使用的 html

fullscreen.html

<!DOCTYPE HTML>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>
  <button id="fullscreen" onClick="checkFullscreen()">Check Fullscreen</button>
  <canvas id="canvas"></canvas>
  <script src="fullscreen.js"></script>
</body>

</html>

这是我的目录中仅有的两个文件——没有 tsconfig、node_modules 等。为了以防万一它有用,这是我的打字稿版本

tsc --version
Version 3.3.3

etid:此 api 的文档

标签: typescriptvisual-studio-codehtml5-canvas

解决方案


3.3 版左右对 TypeScript 的更改破坏了全屏支持。

您的 VS Code 可能使用的是支持全屏 API 的旧 TypeScript 版本。VS Code 的右下角显示了它的 TypeScript 版本。

两种可能的解决方案:

  1. 按照此答案的建议添加您自己的类型定义或
  2. 使用 .降级命令行的 TypeScript 版本npm install -g typescript@3.0

推荐阅读