TypeScript 错误 TS2339:“EventTarget"类型上不存在属性“匹配" [英] TypeScript error TS2339: Property 'matches' does not exist on type 'EventTarget'

查看:22
本文介绍了TypeScript 错误 TS2339:“EventTarget"类型上不存在属性“匹配"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了一个我无法从 TypeScript 中理解的错误.我正在使用一段完全有效的 JavaScript,但它在我的 IDE 和通过 Gulp 进行预处理期间都标记了一个错误.

I'm getting an error that I just cannot fathom from TypeScript. I'm using a perfectly valid piece of JavaScript but it's flagging an error, both in my IDE and during pre-processing via Gulp.

我已将其剥离回其核心,但仍然出现错误(即使这是 完全有效的JS).

I've stripped it back to its core and I'm still getting an error (even though this is perfectly valid JS).

document.addEventListener('click', function (event) {
    console.log(event.target.matches('.click-me'));
}, false);

TypeScript 编译失败并出现以下错误:

TypeScript fails compilation with the following error:

错误 TS2339:EventTarget"类型上不存在属性匹配".

我检查了我的 TypeScript 选项,它们应该允许我使用匹配".没有问题.

I've checked my TypeScript options and they should allow me to use "matches" without issue.

let tscOptions = {
    allowSyntheticDefaultImports: true,
    target: "es5",
    lib: [
        "dom",
        "es7",
        "scripthost",
        "es2017"
    ],
    module: "commonjs"
};

我使用的是 TypeScript 4.1.2 版和 Gulp Typescript v6.0.0-alpha.1.

I'm using version 4.1.2 of TypeScript and v6.0.0-alpha.1 of Gulp Typescript.

这显然是某个地方的配置问题,但我不知道在哪里.

It's obviously a configuration issue somewhere, but I don't know where.

推荐答案

首先——这取决于你如何定义有效的 JS!是的 - 您的 JS 将在所有时间(几乎所有?)工作,但这并不意味着 100% 的时间都可以保证.

First - it depends on how you define valid JS! Yes - your JS will work (almost all?) of the time, but this doesn't mean it's guaranteed 100% of the time.

这里的问题是 .matches 是 Element 类型的对象的属性.event 可以为 null - event.target 为 null 或 EventTarget.

The problem here is that .matches is a property of objects of type Element. event can be null - and event.target is either null or an EventTarget.

一个元素(你想要的类型)扩展了 Node 类型,它扩展了 EventTarget 类型.所以,你不能保证得到你期望的类型,因此 TS 警告你是正确的.

An Element (the type you want) extends the Node type, which extends the EventTarget type. So, you're not guaranteed to be getting the type you expect, therefore TS is correct to warn you.

但是,忽略这些警告可能非常适合您的用例 - 在这种情况下,您可以直接转换它:

It may be perfectly suitable for your use-case to ignore these warnings however - in which case you can just cast it:


document.addEventListener('click', function (event) {
    if (event !== null && event.target !== null) {
       const element = event.target as Element;

       const isMatch = element.matches('foo');
    }
}, false);

为每个边缘情况 IMO 编写大量逻辑来验证没有多大意义 - 但您可以在此处了解有关该问题的更多信息:https://github.com/Microsoft/TypeScript/issues/29540

There's not much point in writing tons of logic to verify for every edge case IMO - but you can learn more about the issue here: https://github.com/Microsoft/TypeScript/issues/29540

这篇关于TypeScript 错误 TS2339:“EventTarget"类型上不存在属性“匹配"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆