Kurs Vue.js · Moduł 15: TypeScript i Nuxt
Typowanie ref, reactive i computed
W tej lekcji5
W systemach stacji kosmicznej każda wartość ma swój precyzyjny typ. Vue 3 Composition API doskonałe wspiera TypeScript - ref, reactive i computed mogą być w pełni typowane.
Typowanie ref
ref przyjmuje typ generyczny Ref<T>:
<script setup lang="ts">
import { ref, type Ref } from 'vue'
// Wnioskowanie typu (type inference)
const count = ref(0) // Ref<number>
const name = ref('NOVA LAB') // Ref<string>
// Jawne typowanie
const status = ref<string>('active')
const data = ref<number[]>([1, 2, 3])
// Typ unii - przydatny gdy wartość może być null
const selectedId = ref<string | null>(null)
// Typ Ref jawnie
const temperature: Ref<number> = ref(-63)
</script>Typowanie reactive
reactive automatycznie wnioskuje typy z obiektu:
<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 zna dokładną strukturę
station.power = 95 // OK
// station.power = 'high' // BŁĄD! number oczekiwany
// station.unknown = true // BŁĄD! Nieznana właściwość
</script>Typowanie computed
computed automatycznie wnioskuje typ zwracanej wartości:
<script setup lang="ts">
import { ref, computed } from 'vue'
const power = ref(85)
const maxPower = ref(100)
// Typ wnioskowany: ComputedRef<number>
const powerPercentage = computed(() => {
return (power.value / maxPower.value) * 100
})
// Typ wnioskowany: ComputedRef<string>
const powerStatus = computed(() => {
if (power.value > 80) return 'optimal'
if (power.value > 40) return 'moderate'
return 'critical'
})
// Jawne typowanie
const label = computed<string>(() => {
return 'Power: ' + powerPercentage.value.toFixed(1) + '%'
})
</script>Writable computed z typami
<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 stanie się 20
</script>Typowanie tablic reaktywnych
<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 sprawdzi poprawność argumentów
addLog('System started', 'info') // OK
// addLog('Error', 'critical') // BŁĄD! 'critical' nie jest valid
</script>Kod do tej lekcji: App.vue
<script setup lang="ts">
import { ref, reactive, computed, type Ref } from 'vue'
// --- Typowanie ref ---
const power = ref<number>(85)
const stationName = ref<string>('NOVA LAB')
const selectedModule = ref<string | null>(null)
// --- Typowanie reactive ---
interface SystemStatus {
oxygen: number
temperature: number
pressure: number
alerts: string[]
}
const systemStatus = reactive<SystemStatus>({
oxygen: 98.5,
temperature: -63,
pressure: 0.6,
alerts: []
})
// --- Typowanie computed ---
const powerStatus = computed<string>(() => {
if (power.value > 80) return 'Optymalny'
if (power.value > 40) return 'Umiarkowany'
return 'Krytyczny'
})
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
})
// Tablica logow z typem
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>Energia</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>Tlen</h3>
<div class="value" :class="{ warning: oxygenWarning }">{{ systemStatus.oxygen }}%</div>
<div class="label">{{ oxygenWarning ? 'Uwaga! Niski poziom' : 'Norma' }}</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>Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jak poprawnie typować ref, który może być string lub null?
2. Czy TypeScript automatycznie wnioskuje typ zwracanej wartości computed?
To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Edytor kodu
Typuj ref, computed i interfejs SystemLog.
- Edytor kodu
Stwórz typowany stan stacji z interfejsem i reactive<StationState>().
- Klikanie w kolejności
Ułóż elementy writable computed z typami:
- Edytor kodu
Zdefiniuj template ref z poprawnym typem i użyj go w onMounted.
- Układanie w poziomie
Ułóż poprawną składnię reactive z interfejsem:
Zadania po tej lekcji
- Zadanie z kodemPraktyka: ref i computed z typami
- Zadanie z kodemPraktyka: Typowane reactive
- PytanieTypowanie ref z unią
- PytanieWnioskowanie computed
- Kliknij w kolejnościTypowanie writable computed
- Zadanie z kodemPraktyka: Template Ref z typem
- Ułóż w kolejnościTypowanie reactive z interfejsem
- PytanieTyp Ref importowany