'How to type a function that only accepts a Readonly Ref in Vue 3?

In Vue 3, you can create a readonly ref or reactive by simply wrapping it with readonly(myRef).

Is there a way to enforce a function is called only with a Readonly Ref at compile time?

e.g. this should be a compile error:

const name = ref('Susan');

function blah(someRef: Readonly<any>) {
  // ...
}

blah(name);


Solution 1:[1]

The comment by nogridbag is correct. Use the DeepReadonly type:

import { readonly, ref } from 'vue'; // or from '@vue/composition-api'
import type { DeepReadonly } from 'vue'; // or from '@vue/composition-api'

const name = ref('Susan');
const readonlyName = readonly(name); // type: DeepReadonly<Ref<string>>

function blah(someRef: DeepReadonly<any>) {
  // ...
}

blah(name);
blah(readonlyName);

Solution 2:[2]

You would use the Ref type:

import type { Ref } from "vue";

function blah(someRef: Ref<string>) {
  // ...
}

You may find however, that it is better to pass values around, rather than refs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Bayard Randel