Javascript is required
·
1 min read

Vue Tip: Typing Component Events

Vue Tip: Typing Component Events Image

To declare emits with full type inference support, we can use the defineEmits API, which is automatically available inside <script setup>:

Component.vue
1<script setup>
2const emit = defineEmits(['change', 'delete'])
3</script>

defineEmits is a compiler macro only usable inside <script setup>. It does not need to be imported and is compiled away when <script setup> is processed. defineEmits provide proper type inference based on the options passed.

Using TypeScript, it is also possible to declare props and emits using pure type annotations:

Component.vue
1<script setup>
2const emit = defineEmits<{
3  (e: 'change', id: number): void
4  (e: 'delete', value: string): void
5}>()
6</script>

defineEmits can only use either runtime declaration OR type declaration. Using both at the same time will result in a compile error.

Warning

Currently, complex types and type imports from other files are not supported.

The type declaration argument must be one of the following to ensure correct static analysis:

  • A type literal
  • A reference to an interface or a type literal in the same file ::

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.