Subscribe on changes!

Can't create a ref with a possibly null type

avatar
Feb 5th 2021

Version

3.0.5

Reproduction link

https://codesandbox.io/s/possibly-null-ref-oeive?file=/src/index.ts

Steps to reproduce

Create a ref whose type is possibly null (e.g. number | null).

import { ref, Ref } from "vue";

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

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

What is expected?

The ref's type is Ref<{ key: number }>

What is actually happening?

The ref's type should be Ref<{ key: number } | null>


I need the ref to be possibly null so that I'm forced in my code to do proper type-checking of the null value condition. I want the type checker to error when I do firstRef.value.key + 1 and force me to do something like (firstRef.value?.key ?? 0) + 1.