首页 > 解决方案 > 无法创建可能为 null 类型的 Vue ref

问题描述

在 Vue v3 中,我想创建一个类型可能为 null 的 ref。在我的应用程序中,它表示从 null 开始直到完成加载的数据。

作为一个人为的例子:

const firstRef: Ref<{ key: number } | null> = ref(null);

// This should give an error because firstRef.value might be null, but it only errors at runtime
const sum: number = firstRef.value.key + 1;

每当我将鼠标悬停firstRef在 VSCode 中的类型上时,它总是将类型显示为Ref<{ key: number }>没有| null. 难道我做错了什么?或者由于某种原因不可能创建一个可能为空的引用?

标签: typescriptvue.js

解决方案


原来这个问题与 Vue 无关。这个问题没有出现"strict": true在我compilerOptions的 in 中tsconfig.json


推荐阅读