Witaj w Laboratorium Kwantowym NOVA LAB! Rok 2087 — systemy stacji kosmicznej wymagają najwyższej precyzji. Każdy błąd w typie danych może doprowadzić do katastrofy. Dlatego nasi inżynierowie używają TypeScript — statycznego systemu typów, który wykrywa błędy jeszcze zanim kod zostanie uruchomiony.
TypeScript to nadzbiór JavaScriptu, który dodaje typy statyczne. W połączeniu z Vue 3 daje nam:
Tworzenie projektu Vue z TypeScript jest proste dzięki Vite:
1npm create vite@latest nova-lab -- --template vue-tsVite automatycznie konfiguruje TypeScript i tworzy plik
tsconfig.json:1{
2 "compilerOptions": {
3 "target": "ES2020",
4 "module": "ESNext",
5 "moduleResolution": "bundler",
6 "strict": true,
7 "jsx": "preserve",
8 "paths": {
9 "@/*": ["./src/*"]
10 }
11 },
12 "include": ["src/**/*.ts", "src/**/*.vue"]
13}W komponentach Vue SFC (Single File Components) dodajemy
lang="ts" do bloku <script setup>:1<script setup lang="ts">
2import { ref } from 'vue'
3
4const stationName = ref<string>('NOVA LAB')
5const crewCount = ref<number>(42)
6const isOnline = ref<boolean>(true)
7</script>Bez
lang="ts" Vue traktuje kod jako zwykły JavaScript. Z lang="ts" kompilator TypeScript sprawdza typy i wychwytuje błędy.1<script setup lang="ts">
2import { ref } from 'vue'
3
4// Proste typy
5const name: string = 'Mars Station'
6const year: number = 2087
7const active: boolean = true
8
9// Tablice
10const modules: string[] = ['Lab', 'Hangar', 'Bridge']
11const temperatures: number[] = [-63, -58, -71]
12
13// Ref z typem generycznym
14const status = ref<string>('operational')
15const energy = ref<number>(98.5)
16</script>TypeScript automatycznie wnioskuje (infer) typy, więc nie zawsze trzeba je podawać jawnie:
1const count = ref(0) // ref<number> — wnioskowane automatycznie
2const label = ref('test') // ref<string> — wnioskowane automatycznieJawne typowanie jest przydatne, gdy typ nie może być wnioskowany:
1const data = ref<string | null>(null) // może być string lub nullInterfejsy definiują kształt obiektów:
1interface CrewMember {
2 id: number
3 name: string
4 role: string
5 active: boolean
6}
7
8const engineer: CrewMember = {
9 id: 1,
10 name: 'Dr. Nova',
11 role: 'Chief Engineer',
12 active: true
13}