</>
Skip to content
Vue lessons (36/43)

Vue — TypeScript

Setup TypeScript

npm create vue@latest my-app
# Select "Add TypeScript? Yes"

Component with TypeScript

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

export default defineComponent({
  data() {
    return {
      count: 0 as number
    }
  },
  methods: {
    increment(): void {
      this.count++
    }
  }
})
</script>

Props with TypeScript

<script lang="ts">
import { defineComponent, PropType } from 'vue'

interface User {
  id: number
  name: string
}

export default defineComponent({
  props: {
    user: {
      type: Object as PropType<User>,
      required: true
    },
    count: {
      type: Number,
      default: 0
    }
  }
})
</script>

Script setup with TypeScript

<script setup lang="ts">
interface Props {
  title: string
  count?: number
}

const props = withDefaults(defineProps<Props>(), {
  count: 0
})

const emit = defineEmits<{
  (e: 'update', value: number): void
}>()

const count = ref(props.count)

function increment() {
  count.value++
  emit('update', count.value)
}
</script>

Refs with TypeScript

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

const count = ref<number>(0)
const message = ref<string>('Hello')
const user = ref<{ name: string; age: number } | null>(null)
</script>

Template refs

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

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

onMounted(() => {
  inputRef.value?.focus()
})
</script>

<template>
  <input ref="inputRef">
</template>

Mini Practice

  1. Convert a component to TypeScript
  2. Add typed props
  3. Use typed refs
  4. Define emit types

Up Next

Continue with Composition API - Modern Vue.

Related Topics

Frequently Asked Questions about TypeScript

What is TypeScript in Vue?

TypeScript is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn TypeScript?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn TypeScript.

Why is TypeScript important in Vue?

TypeScript is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.