How to make every object property reactive?

Consider this simplified example:

interface Dog {
  name: string;
  age: number;
}

const puppy: Dog = {
  name: 'Snoop',
  age: 2,
};

I want to create a reactive reference for each property in the puppy object.

The easiest way is to do this:

const puppyName = ref(puppy.name);
const puppyAge = ref(puppy.age);

However, this is quite repetitive, so I’m wondering: is there a more generic and type-safe approach to achieve the same?

>Solution :

How about doing it manually?

<script setup  lang="ts">
import { ref, Ref } from 'vue'

function createReactiveRefs<T>(obj: T): { [K in keyof T]: Ref<T[K]> } {
  const reactiveRefs: any = {};

  for (const key in obj) {
    reactiveRefs[key] = ref(obj[key]);
  }

  return reactiveRefs;
}

interface Dog {
  name: string;
  age: number;
}

const puppy: Dog = {
  name: 'Snoop',
  age: 2,
};

const reactivePuppy = createReactiveRefs(puppy);
</script>

<template>
  {{ reactivePuppy.name.value }}
</template>

Leave a Reply