7

Vetur 在下面这一行加下划线:

const firstRef = ref<HTMLElement>(null)
没有重载匹配此调用。
 Overload 1 of 3, '(raw: HTMLElement): Ref',给出了以下错误。
  “null”类型的参数不能分配给“HTMLElement”类型的参数。
 Overload 2 of 3, '(raw: HTMLElement): Ref',给出了以下错误。
  “null”类型的参数不能分配给“HTMLElement”类型的参数。Vetur(2769)

这是一个浓缩的上下文。任何想法我做错了什么?

<template>
  <input id="first" ref="firstRef">
  <button type="button" @click.prevent="focusFirst">Focus</button>
</template>

<script lang="ts">
import { defineComponent, ref } from "@vue/composition-api"
export default defineComponent({
  name: "Test",
  setup() {
    const firstRef = ref<HTMLElement>(null)
    const focusFirst = () => {
      const theField = firstRef.value
      theField.focus()
    }

    return { focusFirst }
  }
</script>
4

2 回答 2

10

正如 Vetur 所说,您不能将null类型转换为HTMLELement类型。解决此问题的一种可能方法是编写:

const firstRef = ref<HTMLElement | null>(null)

但是,请记住,null每次要使用 firstRef 时,您都必须检查它是否属于类型。你也可以这样做:

if (firstRef.value) {
  // do stuff with firstRef
  // typescript knows that it must be of type HTMLElement here.
}
于 2020-07-21T21:40:53.710 回答
0

另一种方法可能是可选链接(自 TS 3.7 起):

firstRef.value?.focus()

这对于 TS 来说很好,并且只有在firstRef.value不为空或未定义时才执行命令。

于 2020-09-30T12:39:16.957 回答