kenshin9
kenshin9

Reputation: 2365

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)?

Upvotes: 3

Views: 2091

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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

Upvotes: 2

Related Questions