如何处理联合DOM事件类型?

时间:2020-03-26 23:07:57

标签: typescript dom events

是否可以稍后正确检查事件类型,以便下面的代码变为安全类型。从现在起,出现以下警告:

  Property 'key' does not exist on type 'ClipboardEvent'
Property 'clipboardData' does not exist on type 'KeyboardEvent | ClipboardEvent'.
  Property 'clipboardData' does not exist on type 'KeyboardEvent'.ts(2339)

这是下面的代码和框中的代码的实时副本: https://codesandbox.io/s/hardcore-hugle-i8w1j

function cleanInputValue (event: KeyboardEvent | ClipboardEvent): void {
  let incomingValue: string = ``

  switch (true) {
    case typeof event.key !== `undefined`:
      incomingValue = event.key
      break
    case typeof event.clipboardData !== `undefined`:
      incomingValue = event.clipboardData.getData(`text`)
  }
}

2 个答案:

答案 0 :(得分:2)

您可以为此编写自己的类型保护。

function cleanInputValue (event: KeyboardEvent | ClipboardEvent): void {
  let incomingValue: string = ``;

  if ('key' in event) {
    incomingValue = event.key
  } else if ('clipboardData' in event && event.clipboardData) {
    incomingValue = event.clipboardData.getData(`text`)
  }
}

if else正在检查联合类型的属性key,并将其范围缩小到KeyboardEvent。与ClipboardEvent类似,检查从您定义的联合类型缩小到ClipboardEvent

User type guard TS Docs

答案 1 :(得分:1)

我建议使用Typescript方式-您需要定义两个返回类型为类型谓词的函数:ClipboardEventKeyboardEvent。 (Document

检查event是否为ClipboardEvent:

function isClipboardEvent(event: KeyboardEvent | ClipboardEvent): event is ClipboardEvent {
  return (event as ClipboardEvent).clipboardData !== undefined
}

再次,检查event是否为KeyboardEvent:

function isKeyboardEvent(event: KeyboardEvent | ClipboardEvent): event is KeyboardEvent {
  return (event as KeyboardEvent).key !== undefined
}

现在,在cleanInputValue函数中,只需检查您的event对象并执行任务:

function cleanInputValue(event: KeyboardEvent | ClipboardEvent): void {
  let incomingValue: string = ``

  if (isClipboardEvent(event) && event.clipboardData) { // clipboardData can be null
    incomingValue = event.clipboardData.getData(`text`)
  } else if (isKeyboardEvent(event)) {
    incomingValue = event.key
  }
}