0
0
Vueframework~5 mins

Typing computed properties in Vue

Choose your learning style9 modes available
Introduction

Typing computed properties helps your code know what kind of value to expect. This makes your app safer and easier to understand.

When you want to create a value that changes based on other data in your Vue component.
When you want to make sure TypeScript knows the exact type of the computed value.
When you want to avoid mistakes by catching type errors early.
When you want better code suggestions and auto-completion in your editor.
Syntax
Vue
import { computed } from 'vue'

const myComputed = computed<Type>(() => {
  // return a value of type Type
})

You add the type inside angle brackets <Type> right after computed.

The function inside computed returns the value you want, and TypeScript checks it matches the type.

Examples
This example types the computed property as a number because it returns a number.
Vue
import { computed, ref } from 'vue'

const count = ref(5)
const doubleCount = computed<number>(() => count.value * 2)
Here, the computed property returns a string, so we type it as string.
Vue
import { computed, ref } from 'vue'

const firstName = ref('Jane')
const lastName = ref('Doe')
const fullName = computed<string>(() => `${firstName.value} ${lastName.value}`)
This example shows typing with an interface and a computed property returning a string.
Vue
import { computed, ref } from 'vue'

interface User {
  name: string
  age: number
}

const user = ref<User>({ name: 'Sam', age: 30 })
const userName = computed<string>(() => user.value.name)
Sample Program

This Vue component uses typed computed properties to calculate the total price. The total is typed as a number, so TypeScript helps ensure the calculation is correct.

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

const price = ref(100)
const quantity = ref(3)

const total = computed<number>(() => price.value * quantity.value)
</script>

<template>
  <div>
    <p>Price: {{ price }}</p>
    <p>Quantity: {{ quantity }}</p>
    <p><strong>Total: {{ total }}</strong></p>
  </div>
</template>
OutputSuccess
Important Notes

Typing computed properties is optional but recommended for better code safety.

If you don't specify a type, TypeScript tries to guess it from the return value.

Use ref for reactive data and computed for values derived from that data.

Summary

Typing computed properties helps catch errors early and improves code clarity.

Use computed<Type>(() => value) to specify the type.

This works well with ref and other reactive Vue features.