阿里云主机折上折
  • 微信号
Current Site:Index > Integration of Responsive Design with TypeScript

Integration of Responsive Design with TypeScript

Author:Chuan Chen 阅读数:2942人阅读 分类: Vue.js

Integration of Reactivity with TypeScript

Vue.js's reactivity system is one of its core features. Combined with TypeScript's type-checking capabilities, it can significantly improve code maintainability and development experience. Through type definitions and interface constraints, developers can more clearly describe data structures and component behavior, reducing runtime errors.

Reactivity Basics and Type Definitions

Vue 3's reactive and ref functions can be directly integrated with TypeScript's type system. When adding type annotations to reactive variables, it is recommended to use generic syntax:

import { ref, reactive } from 'vue'

// Primitive types use ref
const count = ref<number>(0) // Explicitly specify number type

// Object types use reactive
interface User {
  id: number
  name: string
  age?: number // Optional property
}

const user = reactive<User>({
  id: 1,
  name: 'Alice'
})

When accessing these reactive variables, TypeScript automatically provides type hints and checks:

user.name.toLowerCase() // Correct
user.age?.toFixed(2)   // Correctly handles optional property
count.value = 'hello'  // Type error: cannot assign string to number

Type-Safe Component Props

In the Composition API, the defineProps macro can achieve both runtime declaration and type inference:

<script setup lang="ts">
const props = defineProps<{
  title: string
  list: Array<{ id: number; text: string }>
  optional?: boolean
}>()

// Full type hints when used
console.log(props.title.length)
</script>

For more complex scenarios, interface definitions can be separated:

interface Product {
  sku: string
  price: number
  inventory: number
}

const props = defineProps<{
  products: Product[]
  maxVisible?: number
}>()

Type Practices for Composable Functions

When encapsulating custom hooks, special attention should be paid to the return value types:

import { ref, onMounted } from 'vue'

export function useFetch<T>(url: string) {
  const data = ref<T | null>(null)
  const error = ref<Error | null>(null)

  onMounted(async () => {
    try {
      const response = await fetch(url)
      data.value = await response.json()
    } catch (err) {
      error.value = err as Error
    }
  })

  return { data, error }
}

When used, full type inference is available:

const { data, error } = useFetch<User[]>('/api/users')

// data is automatically inferred as Ref<User[] | null>
if (data.value) {
  const firstUser = data.value[0] // User type
}

Typing Template Refs

Template refs require explicit element type specification via generics:

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

const inputRef = ref<HTMLInputElement | null>(null)

function focusInput() {
  inputRef.value?.focus() // Safe access
}
</script>

<template>
  <input ref="inputRef" />
  <button @click="focusInput">Focus</button>
</template>

For component refs, InstanceType can be used to obtain the component instance type:

import MyModal from './MyModal.vue'

const modalRef = ref<InstanceType<typeof MyModal> | null>(null)

function openModal() {
  modalRef.value?.show()
}

Type-Safe Event Handling

Custom events can be constrained using type literals:

const emit = defineEmits<{
  (e: 'update', payload: number): void
  (e: 'submit', payload: { values: string[] }): void
}>()

// Type checks are performed when emitting events
emit('update', 42) // Correct
emit('submit', { values: ['a', 'b'] }) // Correct
emit('update', 'text') // Error: Parameter type mismatch

State Management Integration

Pinia integrates seamlessly with TypeScript:

// stores/user.ts
import { defineStore } from 'pinia'

interface UserState {
  list: User[]
  current: User | null
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    list: [],
    current: null
  }),
  actions: {
    async fetchUsers() {
      const res = await api.get<User[]>('/users')
      this.list = res.data
    }
  }
})

Type safety is maintained when used in components:

const store = useUserStore()
store.list[0]?.name // Correctly infers User type

Advanced Type Patterns

Leveraging TypeScript's advanced features allows for more precise types:

type UnwrapRef<T> = T extends Ref<infer U> ? U : T

function useDebouncedRef<T>(value: T, delay = 200) {
  const timeout = ref<NodeJS.Timeout>()
  const debouncedValue = ref<T>(value)

  watch(() => value, (newVal) => {
    clearTimeout(timeout.value)
    timeout.value = setTimeout(() => {
      debouncedValue.value = newVal as UnwrapRef<T>
    }, delay)
  })

  return debouncedValue
}

Type Extensions and Global Declarations

Extending global component type declarations:

// components.d.ts
declare module 'vue' {
  export interface GlobalComponents {
    RouterLink: typeof import('vue-router')['RouterLink']
    BaseButton: typeof import('./components/BaseButton.vue')['default']
  }
}

Typing custom directives:

// directives.d.ts
import { Directive } from 'vue'

declare module 'vue' {
  interface ComponentCustomProperties {
    vFocus: Directive<HTMLInputElement>
  }
}

Type Testing and Validation

Using the asserts keyword to create type assertion functions:

function assertIsDefined<T>(val: T): asserts val is NonNullable<T> {
  if (val === undefined || val === null) {
    throw new Error(`Expected defined but got ${val}`)
  }
}

const maybeUser = ref<User | null>(null)

// After assertion, TypeScript narrows the type
assertIsDefined(maybeUser.value)
console.log(maybeUser.value.id) // Safe access

Performance and Type Optimization

For large reactive objects, use shallowRef and markRaw for performance optimization:

import { shallowRef, markRaw } from 'vue'

const heavyObject = markRaw({
  /* Large immutable data */
})

const optimizedRef = shallowRef(heavyObject) // No deep reactivity

Type Utility Functions

Creating reactive transformation utility types:

type Reactive<T> = {
  [K in keyof T]: T[K] extends object ? Reactive<T[K]> : Ref<T[K]>
}

function createReactive<T extends object>(obj: T): Reactive<T> {
  return reactive(obj) as Reactive<T>
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.