Vue script setup Generics: Building Typed, Reusable Components
AI generated
{ }
Vue.js · TypeScript · Generics · script setup
script setup Generics
building typed, reusable components

A list component that renders rows regardless of whether they represent users, products or orders is a classic case for TypeScript generics, yet Vue components long lacked the right syntax for it. Since Vue 3.3, script setup supports its own generic attribute, letting props, emits and slots bind type-safely to a generic type parameter without falling back on any or unknown. The result is components that behave like generic functions: written once, but usable for arbitrary, concrete item types with full autocompletion.

15 min read
1From which Vue version is the generic attribute in script setup supported?
Since Vue 3.3. Earlier versions have no generic attribute on the script setup tag; generic components had to be awkwardly recreated with the options API through defineComponent instead.
2How do you declare multiple type parameters at once?
As a comma-separated list in the generic attribute, exactly as in plain TypeScript, for example