Back
VueMediumNew

How do you type props and emits in a TypeScript-based `<script setup>` component?

Type-only generic arguments to defineProps/defineEmits

Ideal Answer

With TypeScript, defineProps and defineEmits accept a type parameter instead of a runtime argument, giving full type inference and compile-time checking:

JavaScript
<script setup lang="ts">
interface Props {
  title: string
  count?: number
}
const props = defineProps<Props>()

const emit = defineEmits<{
  update: [id: number]
  delete: []
}>()

function remove() {
  emit('delete')
}
</script>

Default values for type-based props are declared with withDefaults:

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