0
0
Vueframework~5 mins

Typing ref and reactive in Vue

Choose your learning style9 modes available
Introduction

Typing ref and reactive helps your code know what kind of data it holds. This makes your app safer and easier to understand.

When you want to store a simple value like a number or string and keep it reactive.
When you want to store an object or array and track changes inside it.
When you want to catch mistakes early by telling the code what type of data to expect.
When working with TypeScript in Vue to get better code suggestions and error checks.
Syntax
Vue
import { ref, reactive } from 'vue';

const count = ref<number>(0);
const user = reactive<{ name: string; age: number }>({ name: '', age: 0 });

Use ref<Type>() for simple reactive values.

Use reactive<Type>() for reactive objects or arrays.

Examples
This creates a reactive string called message.
Vue
const message = ref<string>('Hello');
This creates a reactive array of numbers called numbers.
Vue
const numbers = reactive<number[]>([1, 2, 3]);
This creates a reactive object profile with typed properties.
Vue
const profile = reactive<{ name: string; active: boolean }>({ name: 'Anna', active: true });
Sample Program

This Vue component uses typed ref for a number and typed reactive for an object. Buttons update the values reactively.

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

const count = ref<number>(0);
const user = reactive<{ name: string; age: number }>({ name: 'John', age: 30 });

function increment() {
  count.value++;
}

function birthday() {
  user.age++;
}
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increase Count</button>

    <p>User: {{ user.name }}, Age: {{ user.age }}</p>
    <button @click="birthday">Happy Birthday!</button>
  </div>
</template>
OutputSuccess
Important Notes

Always access the value inside ref with .value.

reactive wraps objects and arrays, so you access properties directly.

Typing helps catch errors before running your app.

Summary

Use ref<Type> for simple reactive values.

Use reactive<Type> for reactive objects or arrays.

Typing improves safety and developer experience in Vue apps.