Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 3 - Setting the type for a component and its props when used as function parameters

In Vue 3, I'm creating a function that will accept an instance of a component and props to pass through. I'm also using TypeScript and was wondering if I can type those parameters. For example, the function would be something like:

const example = (component, props) => {
  //
};

So my questions would be:

  1. How can I specify a type for a component instance? These are not always going to be the same component, but would at least be components that are used for a similar purpose.
  2. Would there be a way for me to specify the type for the props and confine it to the props that would be for the first parameter (the component)?
like image 392
kenshin9 Avatar asked Oct 28 '25 14:10

kenshin9


1 Answers

You could use many feature provided by typescript and the Component type from vue to achieve your proper typing, make a generic type that extends the Component then infers the component options/props using infer, use Partial to make them optional :

import type { Component } from "vue";

function example<T extends Component>
(Comp: T, props: T extends Component<infer P> ? Partial<P> : never) {
 //....
  }

example(Alert, { variant: "success"})

Note: this also infers the attributes and component instance utilities

like image 124
Boussadjra Brahim Avatar answered Oct 31 '25 03:10

Boussadjra Brahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!