Loading

Argument of type 'HTMLElement | undefined' is not assignable to parameter of type 'HTMLElement'.

问题描述

在ts中我们为变量(比如:A)定义了HTMLElement数据类型或者其他数据类型后,在后续的使用中ts会认为上面绑定的变量(A)可能没有绑定到对应的元素上所以会认为变量的值是在HTMLElement 或者 undefined 两种情况

示例代码:

const chartRef = ref<HTMLElement>()
onMounted(() => {
  const chartInstance = echarts.init(chartRef.value)
  const options = {}
  chartInstance.setOption(options)
})

解决方式

方式1: 禁用strict模式

// tsconfig.json  或者 tsconfig.ts
"strict": true,  ---> "strict": false,

方式2: 使用判断的形式

const chartRef = ref<HTMLElement>()
onMounted(() => {
  if (chartRef.value) {
    const chartInstance = echarts.init(chartRef.value)
    const options = {}
    chartInstance.setOption(options)
  }
})

方式3:使用类型断言(Type Assertion)

const chartRef = ref<HTMLElement>()
onMounted(() => {
  const chartInstance = echarts.init(chartRef.value as HTMLElement)
  const options = {}
  chartInstance.setOption(options)
})
posted @ 2022-09-25 19:15  ^Mao^  阅读(527)  评论(0编辑  收藏  举报