TExcelTAD
Home › Vue › Vue with TypeScript

Vue with TypeScript

Vue 3 is written in TypeScript and has first-class TypeScript support. With types, your editor knows the shape of props, events, refs and stores, catches typos before you run the code, and autocompletes everything. This is a concept lesson: TypeScript in .vue files needs a build step, so the TS code is shown as plain code, and the playgrounds show the same components in JavaScript.

Setting up

Choose TypeScript when scaffolding:

bash · try it yourself
npm create vue@latest my-ts-app -- --typescript
> npx
> create-vue my-ts-app --typescript

┌  Vue.js - The Progressive JavaScript Framework
│
◇  Select features to include in your project:
│  TypeScript

Scaffolding project in /home/me/my-ts-app...
│
└  Done. Now run:

   cd my-ts-app
   npm install
   npm run dev

Then add lang="ts" to the script block of each component:

vue
<script setup lang="ts">
import { ref } from 'vue'
const count = ref(0)   // Ref<number>, inferred
</script>
Tool Role
vue-tsc Type-checks .vue files on the command line (npm run type-check)
Vue - Official (VS Code) Types, errors and autocompletion inside templates
Vite Strips types while building (it does not type-check)

Typing props and emits

With <script setup lang="ts">, props and emits are declared with type arguments — no runtime objects needed:

vue
<script setup lang="ts">
interface Product {
  id: number
  name: string
  price: number
}

const props = defineProps<{
  product: Product
  quantity?: number          // optional
}>()

const emit = defineEmits<{
  add: [id: number, qty: number]   // event name → argument list
  remove: [id: number]
}>()

function addToCart() {
  emit('add', props.product.id, props.quantity ?? 1)
  // emit('add', 'oops')  ❌ Argument of type 'string' is not assignable to 'number'
}
</script>

Default values for optional props come from destructuring (Vue 3.5) or withDefaults:

ts
const { quantity = 1 } = defineProps<{ product: Product; quantity?: number }>()
// or, before 3.5:
const props = withDefaults(defineProps<{ quantity?: number }>(), { quantity: 1 })

The runtime equivalent in JavaScript, runnable here:

html · try it yourself
<div id="app">
  <product-row v-for="p in products" :key="p.id" :product="p" :quantity="2" @add="onAdd"></product-row>
  <p>Cart: {{ cart.join(', ') || 'empty' }}</p>
</div>

<script type="module">
  import { createApp, ref } from 'vue';

  const app = createApp({
    setup() {
      const products = [{ id: 1, name: 'Mug', price: 8 }, { id: 2, name: 'T-shirt', price: 15 }];
      const cart = ref([]);
      const onAdd = (id, qty) => { cart.value.push(`${qty}× #${id}`); };
      return { products, cart, onAdd };
    }
  });

  app.component('product-row', {
    // runtime declaration = what defineProps<…>() compiles to
    props: {
      product: { type: Object, required: true },
      quantity: { type: Number, default: 1 }
    },
    emits: {
      add: (id, qty) => typeof id === 'number' && typeof qty === 'number'
    },
    template: `
      <p>{{ product.name }} — \${{ product.price }}
        <button @click="$emit('add', product.id, quantity)">Add {{ quantity }}</button></p>`
  });

  app.mount('#app');
</script>

Typing refs, reactive and computed

Types are usually inferred from the initial value. Pass a type argument when the initial value doesn't tell the whole story:

ts
import { ref, reactive, computed } from 'vue'
import type { Ref } from 'vue'

const count = ref(0)                       // Ref<number>
const user = ref<User | null>(null)        // starts null, later a User
const ids: Ref<number[]> = ref([])

interface Todo { id: number; text: string; done: boolean }
const state = reactive<{ todos: Todo[]; filter: 'all' | 'open' }>({ todos: [], filter: 'all' })

const openCount = computed(() => state.todos.filter(t => !t.done).length)   // ComputedRef<number>

Template refs and events

ts
import { useTemplateRef, onMounted } from 'vue'

const input = useTemplateRef<HTMLInputElement>('input')   // Vue 3.5
onMounted(() => input.value?.focus())

function onChange(event: Event) {
  console.log((event.target as HTMLInputElement).value)
}

Typing provide/inject

InjectionKey carries the type from provide to inject:

ts
// keys.ts
import type { InjectionKey, Ref } from 'vue'
export const ThemeKey: InjectionKey<Ref<'light' | 'dark'>> = Symbol('theme')

// provider
provide(ThemeKey, theme)

// consumer
const theme = inject(ThemeKey)        // Ref<'light' | 'dark'> | undefined

Types help even in JavaScript

Even without TypeScript, runtime prop validation catches mistakes in development. This playground's validator rejects a wrong status, and the component falls back gracefully:

html · try it yourself
<div id="app">
  <status-pill status="online"></status-pill>
  <status-pill status="away"></status-pill>
  <status-pill status="sleeping"></status-pill>
</div>

<script type="module">
  import { createApp } from 'vue';

  const COLORS = { online: '#22c55e', away: '#f59e0b', offline: '#9ca3af' };
  const app = createApp({});

  app.component('status-pill', {
    props: {
      status: {
        type: String,
        default: 'offline',
        validator: (v) => {
          const ok = v in COLORS;
          if (!ok) console.log(`status-pill: "${v}" is not one of ${Object.keys(COLORS).join(', ')}`);
          return ok;
        }
      }
    },
    template: `
      <span :style="{ background: COLORS[status] || COLORS.offline, color: 'white', padding: '2px 10px', borderRadius: '10px', marginRight: '6px' }">
        {{ status }}
      </span>`,
    setup: () => ({ COLORS })
  });

  app.mount('#app');
</script>

In TypeScript you'd write status?: 'online' | 'away' | 'offline', and status="sleeping" would be a compile error in your editor before you ever run the page.

Tip: Run vue-tsc --noEmit in CI (the scaffold's type-check script does this). Vite's dev server skips type checking for speed, so errors only show in your editor unless you check explicitly.

Note: The Options API can be typed too: wrap the options object in defineComponent({ … }) to get inference for this. The Composition API with <script setup lang="ts"> gives the best results with the least effort.

Test yourself

How do you enable TypeScript in a Single-File Component?

  1. Rename it to .vue.ts
  2. Add lang="ts" to the <script> tag
  3. Import typescript in main.js
  4. It is always on

Which tool type-checks .vue files from the command line?

  1. vite build
  2. vue-tsc
  3. tsc alone
  4. eslint

What type does const user = ref<User | null>(null) have?

  1. User
  2. null
  3. Ref<User | null>
  4. any