技术实践

Vue3+ts中定义ref变量,设置变量类型

在声明文件(*.d.ts)中定义一个类型声明,这样写之后会导致编译报错(vuetur报错)

羊先生的头像
羊先生2021.11.03 · 1 分钟阅读 · 184 阅读
Vue3+ts中定义ref变量,设置变量类型封面
文章正文还需 1 分钟
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)