Vue 3 - Specifying the type of components and props when using them as function parameters
P粉709644700
P粉709644700 2024-01-05 23:55:40
0
1
539

In Vue 3, I'm creating a function that will accept an instance of a component and a property to be passed. I'm also using TypeScript and wondering if I can enter these parameters. For example, the function would look like:

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

So my question is:

  1. How to specify the type of component instance? These are not always the same components, but at least components that serve similar purposes.
  2. Is there a way for me to specify the type of prop and limit it to the prop of the first parameter (component)?


P粉709644700
P粉709644700

reply all(1)
P粉917406009

You can use the many features provided by typescript and the Component types in vue to achieve proper typing, create a generic type that extends Component and then infer 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 properties and component instance utilities

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template