#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 31 of 37medium

How to use TypeScript with Vue?

Type-safe Vue development.

What You'll Learn

  • TypeScript setup
  • Typing props
  • Typing refs and reactive

Setup

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

const count = ref<number>(0)
</script>

Typing Props

code.txtVUE
<script setup lang="ts">
interface Props {
  title: string
  count?: number
  items: string[]
}

const props = withDefaults(defineProps<Props>(), {
  count: 0,
  items: () => []
})
</script>

Typing Emits

code.txtVUE
<script setup lang="ts">
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()

emit('change', 1)
</script>

Typing Refs

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

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

// Component ref
const childRef = ref<InstanceType<typeof ChildComponent> | null>(null)
</script>

Typing Reactive

code.tsTypeScript
interface State {
  count: number
  user: User | null
}

const state = reactive<State>({
  count: 0,
  user: null
})