如何在typescript中将可为null的变量转换为接口



在开发vue3.x类型脚本项目时出现问题。vue文件如下:

<template>
<Comp ref="compRef" />
</template>
<script lang="ts" setup>
import {ref} from "vue";
import Comp from "@/components/Comp";
// This var'value initial with null, but will be filled with reference named "compRef".
const compRef = ref(null);
// 1. Direct call
// compRef.value.Show();  // Rise error "Object is possibly 'null'."
// 2. Transform as a component module
// (compRef.value as Comp).Show();  // Rise error "'Comp' refers to a value, but is being used as a type here. Did you mean 'typeof Comp'?"

// 3. Transform as a interface
// interface IComp { Show: ()=>void; }
// (compRef.value as IComp).Show();  // Rise error "Conversion of type 'null' to type 'IComp' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."
(compRef.value as any).Show();
</script>

将它转换为任何类型都可以解决这个问题,但我确实想将它转换成特定的类型或接口。有什么方法可以将可为null的变量转换为typescript中的接口吗?

我刚刚解决了这个问题!

const compRef = ref<IComp | null>(null);
compRef.value?.Show();

最新更新