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

Viewed 1743

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
}>()
1 Answers

I would recommend to use this option if you don't care about the rest of the keys an their values.

export type SelectOption = {
  id:   string;
  text: string;
  [key: string]: any;
}
//In setup composition api
const props = defineProps({
    options: {
        type: Object as PropType<SelectOption>,
        required: true
    }
})
//Object driven
props: {
    options: {
        type: Object as PropType<SelectOption>,
        required: true
    }
}

//In case of vue-class-component
@Options({
    props: {
        /*...*/
  },
    emits: { /*...*/ },
})

The one you wrote is expecting you to provide a type when declared. This is an example:

type Red<T> = {
   color: "red"
} & T;

type Wine = {
   ageYears: number,
   brand: string,
   origin: "France" | "Italy"
}
// for usage do this
const redWine: Red<Wine> = {
   ageYears: 15,
   brand: "fancy brand",
   origin: "France",
   color: "red"
}
Related