typescriptvue.jsvuejs3

Extracting the prop types of a component in Vue 3 (typescript) to use them somewhere else


Vue can already infer the types of props when you annotate the props under the "props:" key of the component and that is good.

But is there an "utility type" in the vue types which can extract the type of the props from a given component?

Say I have a component defined with defineComponent and the component declaration has a props key which properly defines the names and types of the props. I want an utility type that works like this:

let someting: PropType<MyComponent> = {...};

Vue typescript types contain lots of utility types like this but I couldn't find something that does this.


Solution

  • Figured it out; something like the following works:

    import MyComponent from "./mycomponent.vue";
    
    type MyComponentProps = InstanceType<typeof MyComponent>["$props"];
    
    const props: MyComponentProps = { ... }