Search code examples
javascripttypescriptvue.jsvue-composition-apivue-reactivity

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

  • Use a builtin function toRefs

    interface Dog {
      name: string;
      age: number;
    }
    
    const puppy: Dog = {
      name: 'Snoop',
      age: 2,
    };
    
    import {toRefs} from 'vue'
    
    const puppyRefs = toRefs(puppy)
    // const puppyRefs: ToRefs<Dog>
    
    type Pure<T>={[K in keyof T]: T[K]}
    type PuppyRefs = Pure<typeof puppyRefs>
    // type PuppyRefs = {
    //     name: Ref<string>;
    //     age: Ref<number>;
    // }