Generic components in Vue let you reuse a list without specifying what it will contain. Let’s build one with <script setup lang="ts" generic>.
A while back I wrote Vue 3 with TypeScript Jump-Start, which covered the pieces you need to be productive on day one. Typing props, typing emits, Ref<T> and getting your editor to stop lying to you. That article stopped at the point where most people stop, which is typing a component that knows exactly what it works with.
This one picks up where the types stop being concrete. Let’s say you’ve built a <UserList>. Then somebody needs the same list for products and then for invoices, and now you’re staring at three near-identical components or one component whose props are typed any[].
That’s the problem generic components solve. You write the list once, and it takes on the type of whatever you hand it. The parent gets full autocomplete on the slot props, the emit payloads, everything.
Let’s go ahead and build one!
What Is a Generic Component?
A generic component is a component with a type parameter, the same idea as a generic function in TypeScript. You declare a placeholder type, use it in your props and emits, and the caller fills it in.
The syntax is a generic attribute on the <script setup> tag:
<script setup lang="ts" generic="T">
</script>
That T is now available everywhere inside the block. Whatever you can write between the angle brackets of a generic function, you can write in that attribute. You can constrain T with extends, give it a default, declare a second parameter or point at a type you imported at the top of the file.
A quick note on versions. The generic attribute shipped in Vue 3.3. The tooling around it got better through 3.4 and 3.5, and 3.5 is where reactive props destructure became stable and on by default. That’s the piece that makes prop defaults pleasant on a generic component, we’ll cover it further down.
The Problem, Concretely
Here’s the list component before implementing generics, written for User instances.
UserList.vue
<script setup lang="ts">
type User = {
id: number
name: string
email: string
}
defineProps<{
items: User[]
}>()
const emit = defineEmits<{
select: [user: User]
}>()
</script>
<template>
<ul>
<li v-for="user in items" :key="user.id" @click="emit('select', user)">
{{ user.name }}
</li>
</ul>
</template>
Nothing wrong with this component. It’s typed, it works, your editor helps you inside the template. The only issue is that it’s welded to User.
When the product list request comes in, you have two bad options. Copy the file and swap the type, which means every fix now has to be made twice. Or loosen items to any[] and lose every bit of type safety the component had, both inside it and in the parent.
To be quite honest with you, I’ve shipped both of these at some point, and the any[] version is the one that comes back to bite you later.
The Same List, Generic
TypedList.vue
<script setup lang="ts" generic="T">
defineProps<{
items: T[]
}>()
const emit = defineEmits<{
select: [item: T]
}>()
defineSlots<{
default(props: { item: T }): any
}>()
</script>
<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
@click="emit('select', item)"
>
<slot :item="item" />
</li>
</ul>
</template>
Let’s break it down. The generic="T" attribute introduces the type parameter. From there, T is just a type name you can use anywhere in the block, so items: T[] says “an array of whatever this component was called with.”
The emit declaration uses the same T. That’s the part that matters, because the payload of select is now tied to the items you passed in, not to a type the component picked in advance.
defineSlots is optional here (the tooling can usually work the slot prop type out from <slot :item="item" /> on its own), but I like writing it out on anything reusable. It documents the slot contract at the top of the file where a reader will actually see it, instead of leaving it buried in the template.
Now the parent:
Dashboard.vue
<script setup lang="ts">
import { ref } from 'vue'
import TypedList from './TypedList.vue'
type User = {
id: number
name: string
email: string
}
const users = ref<User[]>([
{ id: 1, name: 'Marina', email: 'marina@myapp.com' },
{ id: 2, name: 'Alex', email: 'alex@myapp.com' },
])
const handleSelect = (user: User) => {
console.log(user.email)
}
</script>
<template>
<TypedList :items="users" @select="handleSelect">
<template #default="{ item }">
{{ item.name }} ({{ item.email }})
</template>
</TypedList>
</template>
Notice how nothing here declares what T is. TypeScript works it out from :items="users", sees a User[], and fills in T as User for the whole component.
The payoff shows up in two places. Inside the slot, item is a User, so item.email autocompletes and item.emial is a red squiggle. And handleSelect is checked against the emit, so if you typed it as (product: Product) you’d get an error at the @select binding instead of a surprise at runtime.
Swap users for a Product[] in a different parent and everything re-infers. Same component file, no changes.
Constraints and keyof T
An unconstrained T means the component can’t assume anything about the items. That’s fine for a simple wrapper, but real components usually need something. A key for v-for, a label to display, a field to sort by.
You could reach for extends and require a shape:
<script setup lang="ts" generic="T extends { id: string | number }">
</script>
Now anything passed in has to have an id, and you can safely write :key="item.id". Pass an array of objects without one and the parent gets an error at the binding.
That works, but it forces every caller into your naming. The version I reach for more often lets the caller pick the field, and still checks that the field exists:
KeyedList.vue
<script setup lang="ts" generic="T">
defineProps<{
items: T[]
itemKey: keyof T
labelKey: keyof T
}>()
</script>
<template>
<ul>
<li v-for="item in items" :key="String(item[itemKey])">
{{ item[labelKey] }}
</li>
</ul>
</template>
This works because of keyof T. The prop accepts only the names of keys that actually exist on the item type. In the parent, typing item-key=" pops open an autocomplete list of id, name, email, and a typo like item-key="nmae" fails to compile.
Directory.vue
<template>
<KeyedList :items="users" item-key="id" label-key="name" />
</template>
I find this pattern most useful in table and picker components. Those are exactly the ones where you end up passing column or field names around as strings and hoping nobody renames anything.
One thing. Notice the String() call around item[itemKey]. keyof T accepts every key on the type, including ones holding objects or dates, and :key wants a string or a number. If you want to be stricter, you can filter the keys by the type of their values.
That takes a small helper, a mapped type you’ll find in plenty of codebases, usually under a different name each time. Since generic can reference imported types, you can keep it out of the component:
types.ts
export type KeysOfType<T, V> = {
[K in keyof T]-?: T[K] extends V ? K : never
}[keyof T]
KeyedList.vue
<script
setup
lang="ts"
generic="T, K extends KeysOfType<T, string | number>"
>
import type { KeysOfType } from './types'
defineProps<{
items: T[]
itemKey: K
labelKey: K
}>()
</script>
Say User grows a createdAt field holding a Date. The parent now gets this:
Directory.vue
<template>
<KeyedList :items="users" item-key="id" label-key="createdAt" />
</template>
The error lands on label-key in the parent, at the exact spot where somebody made the wrong call. KeysOfType<User, string | number> resolves to 'id' | 'name' | 'email', and createdAt simply isn’t in it. The parent can only name fields you can actually render.
The String() call still has to stay in the template. While T is still a placeholder, TypeScript can’t resolve that constraint. It never gets far enough to see that T[K] is a string or a number.
Both key props share one K here, which keeps the signature readable. They don’t have to name the same field, but they are held to the same constraint. If they ever need different ones (a key that can be a number, a label that must be a string), they need a parameter each.
I usually don’t bother with the second version. Two type parameters plus a helper type makes the component harder to read than the extra safety is worth, and a stray [object Object] in a list is a five-second bug to spot. But it’s there when the component is shared widely enough to earn it.
Prop Defaults on a Generic Component
This is the part that got noticeably better in Vue 3.5. withDefaults has always been an odd fit here. It wraps defineProps in another function call, and that extra layer is where generic inference used to break down. Most of those bugs are fixed now, but it still reads like a workaround.
Reactive props destructure, stable and on by default as of 3.5, completely works around the problem. You destructure the props and use plain JavaScript default values:
EmptyableList.vue
<script setup lang="ts" generic="T">
const { items, emptyMessage = 'Nothing here yet' } = defineProps<{
items: T[]
emptyMessage?: string
}>()
</script>
<template>
<p v-if="items.length === 0">{{ emptyMessage }}</p>
<ul v-else>
<li v-for="(item, index) in items" :key="index">
<slot :item="item" />
</li>
</ul>
</template>
items and emptyMessage stay reactive after destructuring, because the compiler prepends props. to those names for you. Generic inference is untouched, since defineProps is called directly.
Big disclaimer though! And this is a whopper.
The compiler does this by rewriting the names, and it rewrites them everywhere in the block. So watch(emptyMessage, ...) would mean watch(props.emptyMessage, ...). That reads the prop once and passes the result, which leaves watch holding a string it has no way to track.
The compiler catches this one and fails the build with an error telling you to pass a getter instead. Here’s that fix:
EmptyableList.vue
<script setup lang="ts" generic="T">
import { watch } from 'vue'
// ...props destructured as above
watch(() => emptyMessage, (value) => {
console.log('changed to', value)
})
</script>
The getter body is still inside <script setup>, so emptyMessage becomes props.emptyMessage there too, and now it’s read fresh on every run.
Same rule for composables. Pass () => emptyMessage rather than the value. The compiler only checks watch and toRef, so that one is on you. It’s the rule you already follow for props, just easier to forget now that they look like ordinary variables.
When Inference Can’t Do It
Inference works when a prop carries the type in. Sometimes nothing does. Picture a select component that fetches its own options from an endpoint you pass as a string:
RemoteSelect.vue
<script setup lang="ts" generic="T extends { id: number; label: string }">
import { ref, onMounted } from 'vue'
import type { Ref } from 'vue'
const { endpoint } = defineProps<{
endpoint: string
}>()
const emit = defineEmits<{
change: [option: T]
}>()
const options = ref([]) as Ref<T[]>
const error = ref('')
const loadOptions = async () => {
const response = await fetch(`https://myapp.com${endpoint}`)
if (!response.ok) {
throw new Error('Failed to load options')
}
options.value = await response.json()
}
onMounted(() => {
loadOptions().catch(() => {
error.value = 'Could not load the options for this field.'
})
})
const handleChange = (event: Event) => {
const id = Number((event.target as HTMLSelectElement).value)
const selected = options.value.find((option) => option.id === id)
if (selected) {
emit('change', selected)
}
}
</script>
<template>
<p v-if="error">{{ error }}</p>
<select v-else @change="handleChange">
<option v-for="option in options" :key="option.id" :value="option.id">
{{ option.label }}
</option>
</select>
</template>
Let’s break it down.
The constraint on T is what lets the template read option.id and option.label without complaint, since every option is guaranteed to have both.
I pulled loadOptions out into its own function so the onMounted callback stays synchronous. Vue does catch errors from an async lifecycle hook, but it sends them to the app-level error handler, not to your error ref. The user would sit in front of an empty select with nothing telling them why. Calling .catch() yourself keeps the failure where you can show it.
The typing problem is that no prop carries T into the component. TypeScript has nothing to work backward from, so T falls back to the constraint. That’s fine inside the component, and it’s a problem the moment an option travels back out. The change payload is typed as { id: number; label: string } and nothing else, so a parent listening for a selected country gets none of the fields its own Country type has.
Vue Language Tools has an answer for this, a comment directive called @vue-generic that lets the parent state the type by hand:
AddressForm.vue
<template>
<!-- @vue-generic {import('@/types').Country} -->
<RemoteSelect endpoint="/countries" />
<!-- @vue-generic {import('@/types').Currency} -->
<RemoteSelect endpoint="/currencies" />
</template>
The comment goes on the line directly above the component, and the type inside the braces is what T becomes for that one instance. Country still has to satisfy the constraint, so if your Country type calls its fields code and name, you’ll get an error on the comment line rather than on the component. Worth knowing before you spend an afternoon on it.
Two more things. This is a type-checking feature from the tooling rather than something the Vue runtime knows about, so it only does anything if you’re running vue-tsc or working in an editor with the Vue extension. And it’s not the prettiest thing you’ll write this week.
Honestly, when I hit this, I first ask whether the component should be fetching at all. Fetching outside and passing the array in as a prop gives you inference for free and a component that’s much easier to test. Sometimes the self-contained widget really is what you want, though, and this is how you type it.
When Not to Reach for a Generic
Generics are for components that genuinely don’t care about the shape of their data. Lists, tables, pickers, dropdowns, anything that arranges items and hands them back to a slot.
They’re the wrong tool when your component actually does care. Say you have a <UserCard> that reads user.avatarUrl, falls back to initials from user.firstName and shows a badge when user.role is admin. That component works with users. Typing the prop as User says so in one word, and anyone reading the file knows what they’re holding. Make it generic, and you’d need a constraint listing all three fields. That’s the same information in a form that’s harder to read. And you’d have to update it by hand every time the card uses one more field.
The other case I’d skip it is when a component used in exactly one place. The type parameter is real complexity, and it only pays off across several call sites. Write it concrete, and make it generic on the day the second caller shows up.
Wrapping Up
Generic components close the last real gap in Vue’s TypeScript support. Components that work with data shapes they don’t know in advance can now be typed properly, with one attribute. You get inferred slot props, inferred emit payloads and keyof T constraints that make string props check themselves.
For the details, the generic section and the defineSlots section of the <script setup> docs are both short and worth reading, and Reactive Props Destructure covers the defaults behavior in full.
Happy typing!





