We use cookies to enhance your experience on the site
CodeWorlds

Main Project: Typed NOVA LAB Station Panel

Time to combine all the knowledge from this module! We'll create a typed control panel for the NOVA LAB space station that uses TypeScript with Vue 3 and incorporates SSR concepts.

Project Requirements

Our control panel should include:

  1. Typed props — each component declares what data it accepts
  2. Typed emits — events are precisely defined
  3. Typed ref and reactive — the application state is fully typed
  4. Template refs — for direct DOM interaction
  5. Provide/Inject — for passing station configuration

Application Architecture

1// types.ts — central application types
2interface CrewMember {
3  id: number
4  name: string
5  role: 'commander' | 'engineer' | 'scientist' | 'pilot'
6  active: boolean
7}
8
9interface StationModule {
10  id: string
11  name: string
12  status: 'online' | 'offline' | 'maintenance'
13  power: number
14}
15
16interface StationState {
17  name: string
18  crew: CrewMember[]
19  modules: StationModule[]
20  alerts: Alert[]
21}
22
23interface Alert {
24  id: number
25  level: 'info' | 'warning' | 'critical'
26  message: string
27  timestamp: Date
28}

ModuleCard Component with Types

1<script setup lang="ts">
2interface ModuleCardProps {
3  module: StationModule
4  isSelected?: boolean
5}
6
7const props = withDefaults(defineProps<ModuleCardProps>(), {
8  isSelected: false
9})
10
11const emit = defineEmits<{
12  select: [moduleId: string]
13  togglePower: [moduleId: string, newStatus: boolean]
14}>()
15</script>

Panel with Provide/Inject

1<script setup lang="ts">
2import { provide, reactive, type InjectionKey } from 'vue'
3
4interface StationConfig {
5  name: string
6  sector: string
7  year: number
8}
9
10const StationKey: InjectionKey<StationConfig> = Symbol('Station')
11
12provide(StationKey, {
13  name: 'NOVA LAB',
14  sector: 'Alpha-7',
15  year: 2087
16})
17</script>

SSR Considerations

When building an application with SSR in mind (e.g., with Nuxt), remember:

1// Do NOT use browser objects outside of onMounted
2import { onMounted, ref } from 'vue'
3
4const windowWidth = ref(0)
5
6// GOOD — window is only available on the client
7onMounted(() => {
8  windowWidth.value = window.innerWidth
9})
10
11// BAD — window doesn't exist on the server!
12// const width = window.innerWidth  // ERROR in SSR

An SSR-friendly composable:

1function useScreenSize() {
2  const width = ref(0)
3  const height = ref(0)
4
5  onMounted(() => {
6    width.value = window.innerWidth
7    height.value = window.innerHeight
8
9    window.addEventListener('resize', () => {
10      width.value = window.innerWidth
11      height.value = window.innerHeight
12    })
13  })
14
15  return { width, height }
16}

Full Example

Below is an interactive editor with a typed Vue application. Analyze the code and experiment with types — add new properties, change types, and observe how TypeScript helps catch errors.

Go to CodeWorlds