【问题标题】:Silencing a Problem in Visual Studio Code在 Visual Studio Code 中解决问题
【发布时间】:2019-05-05 07:16:25
【问题描述】:

在我的项目中,我有一些代码可以检查支持哪个鼠标滚轮(针对不同的浏览器),因此我们可以正确添加事件侦听器。这是它的外观:

const support = 'onwheel' in document.createElement('div') 
? 'wheel'
: document.onmousewheel !== undefined 
    ? 'mousewheel'
    :'DOMMouseScroll';

它有效。不过,我最近改用Visual Studio Code,现在出现了一个常量问题

“文档”类型上不存在属性“onmousewheel”。

这是一个有效且有用的错误。但是,在这种情况下,我想忽略它,因为这是我正在检查的内容。

有什么方法可以让我只在这一行忽略这个问题?当我使用 TypeScript 时,我尝试过 // tslint:disable-line,但我认为这是 VS Code 本身。任何帮助表示赞赏。

【问题讨论】:

  • document['onmousewheel'], (document as any).onmousewheel

标签: typescript visual-studio-code eslint lint tslint


【解决方案1】:

您看到此问题是因为 DOM 的内置 TypeScript 类型(通常称为 lib.dom.d.ts,因为它们存储在其中的文件名)没有声明 onmousewheel 属性存在于Document 类型。全局document 变量被声明为具有Document 类型。但是,它显然存在于window。可以把代码改成window.onmousewheel吗?

如果你确定必须document.onmousewheel,你可以创建一个新文件(我们称之为typings/lib.custom.d.ts)并声明Document接口也有一个onmousewheel属性:

interface Document {
    onmousewheel: ((this: Document, ev: Event) => any) | null;
}

请注意,此文件不能importexport 任何内容:它旨在声明一个全局可用接口Document,它将向任何预先存在的全局可用接口Document 添加类型。 em>

注意:尝试tslint:disable 在这里没有任何作用,因为您遇到的错误在 TypeScript 中。 TSLint 在 TypeScript 之上提供了额外的检查层,但由于此错误本身是 TypeScript,因此它不是一个因素。你可能会想到@ts-ignore。然而,这应该很少(如果有的话)被使用,并且只能作为最后的手段。正确地通知类型系统某些事情是你认为的方式(就像上面添加的 onmousewheel 接口属性)比完全禁用一行的 TypeScript 要好得多。在一行上禁用 TypeScript 可以忽略其他有效错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多