Subscribe on changes!

Linking refs to reactive objects with Typescript

avatar
Feb 2nd 2021

What problem does this feature solve?

Vue made possible linking a ref to a reactive object by just assigning it like this.

const obj = reactive({ a: 10 });

const a = ref(20);

obj.a = a; // This triggers an error from Typescript

But, as stated, doing this triggers an error from Typescript. Also, it's not totally clear what's really happening... Someone could see the error with the suggestion "change a to a.value" and do it. By doing so, the link from obj.a to the ref a is gone.

What does the proposed API look like?

A nice workaround to this is writting something like

obj.a = a as number & Ref<number>;

But I think it would be nicer if we have an API like this (the name doesn't need to be exactly this)

linkRefs(obj, { a });

This way, it's totally clear what's really happening and Typescript shouldn't complain too :)

Implementing this shouldn't be hard too as it can be just a syntax sugar for that workaround I mentioned before.

avatar
Feb 3rd 2021

You never need that feature, you can just do:

const obj = reactive({ a: 20 });

then, you can use toRef() or toRefs() to get a ref version of a:

const refA = toRef(obj, 'a')
refA.value // 20

// or

const { a: refA } = toRefs(obj)
refA.value // 20
avatar
Aug 30th 2021

In the documentation, there is an example:

const count = ref(0)
const state = reactive({
  count
})

console.log(state.count) // 0

state.count = 1
console.log(count.value) // 1

const otherCount = ref(2)

state.count = otherCount
console.log(state.count) // 2
console.log(count.value) // 1

type check fails at state.count = otherCount.

One use case is, for example, I want to assign a new ref to state.count in a method that will be called by a click. Perhaps there is a better solution.