Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type a Generic component in Vue 3's <script setup>?

I have a Select component that accepts an array of options. Each option can be an object of anything as long as it has the following attributes id and text

So I typed it like this:

type SelectOption<T> = {
  id: string | number
  text: string
} & T

But I'm not sure how to use this with defineProps and also defineEmits in the component.

defineProps<{
  options: SelectOption<??>
  modelValue: SelectOption<??>
}>()

defineEmits<{
  (event: 'update:modelValue', SelectOption<??>): void
}>()
like image 663
Mysterywood Avatar asked Sep 05 '25 03:09

Mysterywood


1 Answers

Here is an updated answer to account for the recent improvements in this area :

  • Vue Language Tools has added support for generic types
  • Support for generic components has been added recently in Vue core 3.3

This allows you to write the following code (from the linked release blog post) :

<script setup lang="ts" generic="T extends string | number, U extends Item">
import type { Item } from './types'
defineProps<{
  id: T
  list: U[]
}>()
</script>

Of course, this requires you to upgrade to the latest versions of vue and volar.

Note that as of writing this (May 2023), this feature is a bit rough around the edges but is still actively developed.

like image 86
Pierre couy Avatar answered Sep 09 '25 03:09

Pierre couy