Is there a way in Typescript to prevent assigning a Ref<string>
to Ref<string | undefined>
when using Vue's ref
function to create typed Ref
objects?
Example
When trying to assign undefined
to a Ref<string>
, an error is expected:
const s1 = ref('hello') // typed as Ref<string>
s1.value = undefined // causes a TS error as expected: "Type 'undefined' is not assignable to type 'string'"
However, it seems possible to assign this reference to another one that supports undefined
, bypassing the type check:
const s2: Ref<string | undefined> = s1 // IMO unsafe assignment -- how to make this illegal?
s2.value = undefined
const s: string = s1.value // TS thinks that the value is still a string, but actually it's undefined
My use case
This issue came up while working on a function that should unset the value of a ref. I would like Typescript support for only accepting refs with valid types:
function unsetRef<T>(r: Ref<T | undefined>) {
r.value = undefined
}
unsetRef(s1) // expected to be ok
unsetRef(s2) // expected to fail, but causes no TS error