search

Home  >  Q&A  >  body text

Vue 3 - Specifying the type of components and props when using them as function parameters

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粉709644700P粉709644700371 days ago552

reply all(1)I'll reply

  • P粉917406009

    P粉9174060092024-01-06 09:36:48

    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

    reply
    0
  • Cancelreply