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

Time:11-17

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

CodePudding user response:

Regarding the first question, the solution is as follows:

InstanceType<typeof MyComponent>

Concerning the second one, you can do as follows:

import MyComponent from "path/to/MyComponent.vue";

type MyComponentProps = InstanceType<typeof MyComponent>["$props"];

Using the two solutions above, your code would look like this:


const example = (component: InstanceType<typeof YourComponent>, props: MyComponentProps) => {
  //
};

CodePudding user response:

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

  • Related