Vue3 Fundamentals · Vue 3 + TypeScript

Typing emits

Typed emits

Typing emits

A child tells its parent something happened by emitting an event. In a <script setup lang="ts"> block you declare the events with the type-only defineEmits<…>() form, and the type says which names exist and what payload each one carries.

<script setup lang="ts">
const emit = defineEmits<{ (event: 'picked', value: string): void }>();
</script>

<template>
  <button @click="emit('picked', 'Vue')">Pick</button>
</template>

The call signature (event: 'picked', value: string) means the component can emit picked, and every picked event carries a string. Emitting an unknown name, or forgetting the payload, is a compile error.

The parent listens with @picked and receives the value as its argument. Because the payload is typed, the parent's handler knows the argument is a string without a cast or a comment. The type is the contract between the two components: change the payload and the parent's handler is checked against the new shape.

In App.vue, emit picked with the value Vue.

Challenge

The button sends the wrong payload when clicked. Export an App component from App.vue that declares a picked event with the type-only defineEmits<{ (event: 'picked', value: string): void }>() form and emits it with the value Vue when the button is clicked.

The Test clicks the button and reads the emitted events. The starter emits picked with an empty string, so the Test fails until you pass Vue.

App.vue
<script setup lang="ts">
const emit = defineEmits<{ (event: 'picked', value: string): void }>();
</script>

<template>
  <button @click="emit('picked', '')">Pick</button>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.