首页 > 解决方案 > 带有 jQ​​uery 事件的打字稿错误

问题描述

我已将一个项目迁移到 Typescript。到目前为止一切都很好,但是我遇到了 jQuery 事件的麻烦。

例如代码

$(document).on('cc.command',
...

打字稿抛出错误

ERROR in [..]/src/modules/command-center.ts
./src/modules/command-center.ts
[tsl] ERROR in [..]/src/modules/command-center.ts(24,18)
      TS2345: Argument of type '"cc.command"' is not assignable to parameter of type 'TypeEventHandlers<Document, (this: Document, e: Event, str: string) => void, Document, Document>'.

同样,使用代码

$('#user-input').keydown(
      function onKeydown(e:KeyboardEvent): void {
...

我收到错误

ERROR in [..|/src/modules/user-interface.ts
./src/modules/user-interface.ts
[tsl] ERROR in [..|/src/modules/user-interface.ts(55,16)
      TS2345: Argument of type '(this: HTMLElement, e: KeyboardEvent) => void' is not assignable to parameter of type 'false | EventHandlerBase<HTMLElement, KeyDownEvent<HTMLElement, null, HTMLElement, HTMLElement>> | undefined'.
  Type '(this: HTMLElement, e: KeyboardEvent) => void' is not assignable to type 'EventHandlerBase<HTMLElement, KeyDownEvent<HTMLElement, null, HTMLElement, HTMLElement>>'.
    Types of parameters 'e' and 't' are incompatible.
      Type 'KeyDownEvent<HTMLElement, null, HTMLElement, HTMLElement>' is missing the following properties from type 'KeyboardEvent': code, location, repeat, getModifierState, and 20 more.

还有一个,有:

$('#user-name').on('blur',
..

我正进入(状态

ERROR in [..|/src/modules/user-interface.ts
./src/modules/user-interface.ts
[tsl] ERROR in [..|/src/modules/user-interface.ts(65,24)
      TS2345: Argument of type '"blur"' is not assignable to parameter of type 'TypeEventHandlers<HTMLElement, (this: HTMLElement, e: KeyboardEvent) => void, HTMLElement, HTMLElement>'.

我已经安装了 jQuery 类型定义,当我设置strictFunctionTypesfalsein时也会出现同样的错误tsconfig.json

我该如何解决这些错误?

我应该提到我正在使用 npm 包 typescript 3.1.6、jquery 3.4.0 和 @types/jquery 3.3.29。

标签: jquerytypescripttypescript-typings

解决方案


推荐阅读