Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Vue TypeScript Typed Props Composables: Tutorial, Examples, FAQs & Interview Tips

Why TypeScript with Vue?

Vue 3 was rewritten in TypeScript and has first-class TypeScript support. Using TypeScript with Vue gives you:

  • Type safety - catch errors at compile time, not runtime
  • Better IDE support - autocomplete, refactoring, go-to-definition
  • Self-documenting code - types serve as documentation
  • Safer refactoring - TypeScript catches breaking changes
Vue + TypeScript - Props, Emits, Refs, Composables
<!-- TypedComponent.vue -->
<template>
  <div>
    <h2>{{ user.name }}</h2>
    <p>{{ user.email }}</p>
    <span :class="`badge-${user.role}`">{{ user.role }}</span>
    <button @click="handleEdit">Edit</button>
    <p>Count: {{ count }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { User, UserRole } from '@/types'

// Typed props with defineProps
interface Props {
  user: User
  editable?: boolean
  maxItems?: number
}

const props = withDefaults(defineProps<Props>(), {
  editable: true,
  maxItems: 10,
})

// Typed emits with defineEmits
interface Emits {
  (e: 'edit', user: User): void
  (e: 'delete', id: number): void
  (e: 'update:user', user: User): void
}

const emit = defineEmits<Emits>()

// Typed refs
const count = ref<number>(0)
const name  = ref<string>('')
const users = ref<User[]>([])
const selectedRole = ref<UserRole | null>(null)

// Typed computed
const isAdmin = computed<boolean>(() => props.user.role === 'admin')
const displayName = computed<string>(() => `${props.user.name} (${props.user.role})`)

// Typed function
function handleEdit(): void {
  emit('edit', props.user)
}

function updateUser(updates: Partial<User>): void {
  emit('update:user', { ...props.user, ...updates })
}

// Typed template ref
import { useTemplateRef } from 'vue'
const inputRef = useTemplateRef<HTMLInputElement>('myInput')

function focusInput(): void {
  inputRef.value?.focus()
}
</script>
// composables/useFetch.ts - typed composable
import { ref, watchEffect, toValue, type MaybeRefOrGetter } from 'vue'

interface FetchState<T> {
    data: T | null
    loading: boolean
    error: string | null
}

export function useFetch<T>(url: MaybeRefOrGetter<string>) {
    const state = ref<FetchState<T>>({
        data: null,
        loading: false,
        error: null,
    })

    watchEffect(async () => {
        const resolvedUrl = toValue(url)
        if (!resolvedUrl) return

        state.value.loading = true
        state.value.error = null

        try {
            const res = await fetch(resolvedUrl)
            if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`)
            state.value.data = await res.json() as T
        } catch (err) {
            state.value.error = err instanceof Error ? err.message : 'Unknown error'
        } finally {
            state.value.loading = false
        }
    })

    return state
}

// Usage with type inference:
// const usersState = useFetch<User[]>('/api/users')
// usersState.value.data  // typed as User[] | null
// usersState.value.loading  // boolean
// usersState.value.error    // string | null

// composables/useCounter.ts
import { ref, computed } from 'vue'

export function useCounter(initialValue: number = 0) {
    const count = ref(initialValue)
    const doubled = computed(() => count.value * 2)
    const isPositive = computed(() => count.value > 0)

    function increment(by: number = 1): void { count.value += by }
    function decrement(by: number = 1): void { count.value -= by }
    function reset(): void { count.value = initialValue }

    return { count, doubled, isPositive, increment, decrement, reset }
}
// types/index.ts - shared type definitions

export type UserRole = 'admin' | 'user' | 'moderator' | 'guest'

export interface User {
    id: number
    name: string
    email: string
    role: UserRole
    avatar?: string
    createdAt: Date
    isActive: boolean
}

export interface ApiResponse<T> {
    data: T
    message: string
    success: boolean
    pagination?: {
        page: number
        perPage: number
        total: number
    }
}

export interface FormField {
    value: string
    error: string | null
    touched: boolean
}

export type FormState<T extends Record<string, unknown>> = {
    [K in keyof T]: FormField
}

// Utility types
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
export type CreateUser = Optional<User, 'id' | 'createdAt' | 'isActive'>
export type UpdateUser = Partial<Omit<User, 'id'>>

// Component prop types
export interface TableColumn<T = unknown> {
    key: keyof T
    label: string
    sortable?: boolean
    width?: string
    align?: 'left' | 'center' | 'right'
    formatter?: (value: T[keyof T], row: T) => string
}

Deep Dive: Typescript in Real Projects

Understanding Typescript is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Typescript.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Typescript.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Typescript focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.