Today, I learned that when you use TypeScript with VueJS, you can create generic components to make them type-safe:
Generic type parameters can be declared using the
genericattribute on the<script>tag:<script setup lang="ts" generic="T">defineProps<{items: T[]selected: T}>()</script>The value of generic works exactly the same as the parameter list between
<...>in TypeScript. For example, you can use multiple parameters, >extendsconstraints, default types, and reference imported types:<scriptsetuplang="ts"generic="T extends string | number, U extends Item">import type { Item } from './types'defineProps<{id: Tlist: U[]}>()</script>In order to use a reference to a generic component in a
refyou need to use the [vue-component-type-helpers](https://www.npmjs.com/package/> vue-component-type-helpers) library asInstanceTypewon't work.<scriptsetuplang="ts">import componentWithoutGenerics from '../component-without-generics.vue';import genericComponent from '../generic-component.vue';import type { ComponentExposed } from 'vue-component-type-helpers';// Works for a component without genericsref<InstanceType<typeof componentWithoutGenerics>>();ref<ComponentExposed<typeof genericComponent>>();
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.