Vue · Senior · Question 36 of 75

How do you write a generic component (e.g. a typed select)?

<script setup lang="ts" generic="T extends { id: string }">
defineProps<{ items: T[]; modelValue: T | null }>();
defineEmits<{ "update:modelValue": [value: T] }>();
</script>

Explanation

The type parameter is inferred from props at the usage site, so slot props and events are typed for the specific item type.

Further reading

Problem with a question

Vue · Senior · question 36

Test yourself

Take the Vue · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz