无法消除Document接口和Document var的歧义

时间:2018-03-11 01:17:17

标签: typescript

TypeScript 2.7.2产生了一个相当令人惊讶的错误。

const handleKeyDown = (document: Document, ev: KeyboardEvent): any => {
  switch (ev.keyCode) {
    case 78: // N
      this.someOtherFunction();
      console.log("Pressed key N");
      break;
    default:
      break;
  }
};

document.addEventListener<'keydown'>('keydown', handleKeyDown)

失败
 error TS2345: Argument of type '(document: Document, ev: KeyboardEvent) => any' 
is not assignable to parameter of type '(this: Document, ev: KeyboardEvent) => any'.

与TypeScript文档的Comparing two functions部分不一致。

但是,在进一步调查中,handleKeyDown的{​​{1}}引用了Document中的interface Document,而lib.dom.d.ts代表addEventListener Document <指>

declare var Document: {
  prototype: Document;
  new(): Document;
};

也在lib.dom.d.ts

我如何得到这个来进行类型检查?

编辑:

  handleKeyDown(document: {
    prototype: Document;
    new: () => Document
  }, ev: KeyboardEvent) { ...

也没有使用

进行类型检查
[ts] Argument of type '(document: { prototype: Document; new: () => Document; }, ev: KeyboardEvent) => void' 
is not assignable to parameter of type '(this: Document, ev: KeyboardEvent) => any'.

1 个答案:

答案 0 :(得分:1)

addEventListener的第二个参数被声明为一个函数,它将事件作为它的第一个参数,并且你传递一个带有两个参数的函数,第一个函数的类型错误 - Document 。声明它的正确方法是

const handleKeyDown = (ev: KeyboardEvent): any => {
  switch (ev.keyCode) {
    case 78: // N
      this.someOtherFunction();
      console.log("Pressed key N");
      break;
    default:
      break;
  }
};


document.addEventListener<'keydown'>('keydown', handleKeyDown)
this: Document声明中的

addEventListener不是一个参数,它只是在调用函数时声明this类型的一种方式,但是从handleKeyDown开始是一个箭头functin,其中this在封闭的上下文中引用this,而不是文档中的<?php session_start(); if($_POST['username']){ $_SESSION['username'] =$_POST['username']; // session run } ?>