Vue.js course ยท Module 15: TypeScript & Nuxt
Typing ref, reactive, and computed
In this lesson5
In the space station systems, every value has its precise type. Vue 3 Composition API has excellent TypeScript support - ref, reactive, and computed can be fully typed.
Typing ref
ref accepts a generic type Ref<T>:
<script setup lang="ts">
import { ref, type Ref } from 'vue'
// Type inference
const count = ref(0) // Ref<number>
const name = ref('NOVA LAB') // Ref<string>
// Explicit typing
const status = ref<string>('active')
const data = ref<number[]>([1, 2, 3])
// Union type - useful when the value can be null
const selectedId = ref<string | null>(null)
// Explicit Ref type
const temperature: Ref<number> = ref(-63)
</script>Typing reactive
reactive automatically infers types from the object:
<script setup lang="ts">
import { reactive } from 'vue'
interface StationState {
name: string
power: number
modules: string[]
coordinates: { x: number; y: number; z: number }
}
const station = reactive<StationState>({
name: 'NOVA LAB',
power: 100,
modules: ['Lab', 'Bridge', 'Hangar'],
coordinates: { x: 0, y: 0, z: 0 }
})
// TypeScript knows the exact structure
station.power = 95 // OK
// station.power = 'high' // ERROR! number expected
// station.unknown = true // ERROR! Unknown property
</script>Typing computed
computed automatically infers the return type:
<script setup lang="ts">
import { ref, computed } from 'vue'
const power = ref(85)
const maxPower = ref(100)
// Inferred type: ComputedRef<number>
const powerPercentage = computed(() => {
return (power.value / maxPower.value) * 100
})
// Inferred type: ComputedRef<string>
const powerStatus = computed(() => {
if (power.value > 80) return 'optimal'
if (power.value > 40) return 'moderate'
return 'critical'
})
// Explicit typing
const label = computed<string>(() => {
return 'Power: ' + powerPercentage.value.toFixed(1) + '%'
})
</script>Writable computed with Types
<script setup lang="ts">
import { ref, computed } from 'vue'
const celsius = ref(20)
const fahrenheit = computed<number>({
get: () => celsius.value * 9/5 + 32,
set: (val: number) => {
celsius.value = (val - 32) * 5/9
}
})
fahrenheit.value = 68 // celsius becomes 20
</script>Typing Reactive Arrays
<script setup lang="ts">
import { ref } from 'vue'
interface LogEntry {
id: number
message: string
level: 'info' | 'warn' | 'error'
timestamp: Date
}
const logs = ref<LogEntry[]>([])
function addLog(message: string, level: LogEntry['level']) {
logs.value.push({
id: Date.now(),
message,
level,
timestamp: new Date()
})
}
// TypeScript checks argument correctness
addLog('System started', 'info') // OK
// addLog('Error', 'critical') // ERROR! 'critical' is not valid
</script>Code for this lesson: App.vue
<script setup lang="ts">
import { ref, reactive, computed, type Ref } from 'vue'
// --- Typing ref ---
const power = ref<number>(85)
const stationName = ref<string>('NOVA LAB')
const selectedModule = ref<string | null>(null)
// --- Typing reactive ---
interface SystemStatus {
oxygen: number
temperature: number
pressure: number
alerts: string[]
}
const systemStatus = reactive<SystemStatus>({
oxygen: 98.5,
temperature: -63,
pressure: 0.6,
alerts: []
})
// --- Typing computed ---
const powerStatus = computed<string>(() => {
if (power.value > 80) return 'Optimal'
if (power.value > 40) return 'Moderate'
return 'Critical'
})
const powerColor = computed(() => {
if (power.value > 80) return '#00ff88'
if (power.value > 40) return '#f39c12'
return '#e74c3c'
})
const oxygenWarning = computed<boolean>(() => {
return systemStatus.oxygen < 90
})
// Typed array of logs
interface LogEntry {
id: number
message: string
level: 'info' | 'warn' | 'error'
}
const logs = ref<LogEntry[]>([])
let logId = 0
function addLog(message: string, level: LogEntry['level']) {
logs.value.push({ id: logId++, message, level })
}
function adjustPower(delta: number) {
power.value = Math.max(0, Math.min(100, power.value + delta))
addLog('Power: ' + power.value + '%', power.value < 30 ? 'error' : 'info')
}
function adjustOxygen(delta: number) {
systemStatus.oxygen = Math.max(0, Math.min(100, systemStatus.oxygen + delta))
addLog('O2: ' + systemStatus.oxygen + '%', systemStatus.oxygen < 90 ? 'warn' : 'info')
}
</script>
<template>
<div class="nova-lab">
<h1>{{ stationName }} - ref, reactive, computed</h1>
<div class="grid">
<div class="panel">
<h3>Power</h3>
<div class="value" :style="{ color: powerColor }">{{ power }}%</div>
<div class="label">{{ powerStatus }}</div>
<div class="controls">
<button @click="adjustPower(-10)" class="btn danger">-10</button>
<button @click="adjustPower(10)" class="btn success">+10</button>
</div>
</div>
<div class="panel">
<h3>Oxygen</h3>
<div class="value" :class="{ warning: oxygenWarning }">{{ systemStatus.oxygen }}%</div>
<div class="label">{{ oxygenWarning ? 'Warning! Low level' : 'Normal' }}</div>
<div class="controls">
<button @click="adjustOxygen(-5)" class="btn danger">-5</button>
<button @click="adjustOxygen(5)" class="btn success">+5</button>
</div>
</div>
</div>
<div class="log-panel" v-if="logs.length > 0">
<div v-for="log in logs" :key="log.id" :class="['log', log.level]">
[{{ log.level.toUpperCase() }}] {{ log.message }}
</div>
</div>
</div>
</template>
<style scoped>
.nova-lab {
background: #0a0e27;
color: #00ff88;
min-height: 100vh;
padding: 20px;
font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 15px; font-size: 18px; }
h3 { color: #00b4d8; margin-bottom: 8px; }
.grid { display: flex; gap: 15px; }
.panel {
flex: 1;
background: rgba(0,180,216,0.08);
border: 2px solid #00b4d8;
padding: 16px;
border-radius: 12px;
text-align: center;
}
.value { font-size: 32px; font-weight: bold; }
.value.warning { color: #e74c3c; }
.label { font-size: 12px; color: #888; margin: 4px 0 12px; }
.controls { display: flex; gap: 8px; justify-content: center; }
.btn {
border: none;
color: white;
padding: 6px 14px;
border-radius: 6px;
cursor: pointer;
}
.success { background: #00ff88; color: #0a0e27; }
.danger { background: #e74c3c; }
.log-panel { margin-top: 15px; }
.log {
padding: 4px 10px;
font-size: 12px;
margin: 2px 0;
border-radius: 4px;
}
.log.info { color: #00b4d8; }
.log.warn { color: #f39c12; }
.log.error { color: #e74c3c; }
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you correctly type a ref that can be string or null?
2. Does TypeScript automatically infer the return type of computed?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Type ref, computed, and the SystemLog interface.
- Code editor
Create a typed station state with an interface and reactive<StationState>().
- Click in order
Arrange the elements of a writable computed with types:
- Code editor
Define a template ref with the correct type and use it in onMounted.
- Horizontal ordering
Arrange the correct reactive syntax with an interface: