技术实践
Vue3+ts中定义ref变量,设置变量类型
在声明文件(*.d.ts)中定义一个类型声明,这样写之后会导致编译报错(vuetur报错)

html
<template>
<el-input ref="input"></el-input>
</template>
//....
import {Ref, ref} from 'vue'
const input: Ref<HTMLElement> = ref(null)
这样写之后会导致编译报错(vuetur报错)
js
Type 'Ref<null>' is not assignable to type 'Ref<HTMLElement>'.
Type 'null' is not assignable to type 'HTMLElement'.Vetur(2322)
解决办法
增加null类型
js
const input: Ref<HTMLElement | null> = ref(null)
在声明文件(*.d.ts)中定义一个类型声明
js
// 定义声明
declare type Nullable<T> = T | null
// 使用的地方只需要
const input: Ref<Nullable<HTMLElement>> = ref(null)