QA
Senior LevelVue JS

How do you use generic type parameters in <script setup lang="ts" generic="T extends ...">?

❓ Interview Prompt: Explain Vue 3.3+ generic component declaration (generic="T"), reusable DataTable<T> components, and prop/emit type inference.

Before Vue 3.3, writing reusable generic components (like a '<DataTable<T>>' or '<Select<T>>') required cumbersome workaround setups.

Generic Components (Vue 3.3+):

Add the 'generic="T extends Record<string, any>"' attribute to the '<script setup>' tag. Prop definitions and emitted event signatures inherit the exact generic type 'T' passed by the parent component!

Code Implementation Example

html
<!-- DataTable.vue (Generic Vue 3.3+ Component) -->
<script setup lang="ts" generic="T extends { id: number | string }">
defineProps<{
  items: T[];
  selectedItem?: T;
}>();

const emit = defineEmits<{
  (e: 'select', item: T): void;
}>();
</script>

<template>
  <div v-for="item in items" :key="item.id" @click="emit('select', item)">
    <slot :item="item" />
  </div>
</template>
💡Building a generic Vue 3.3+ component using script setup generic="T" attribute.
🎯 Interview Key Takeaway

Use generic="T" on <script setup> in Vue 3.3+ to create type-safe generic components like DataTables and Selects.

#Generics#TypeScript#script setup#Vue 3.3#Senior
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?