J. Vergeer
J. Vergeer

Reputation: 800

Is there a way to get the type of a component in vuejs?

I am building a vuejs application in typescript. I want to make maximum use of the typings available.

Most of the time the typings and type inference just works fine.

In some pieces of code I would like to pass a reference to a specific component type. i.e.

const MyComponent = Vue.extend({...});

function myFunction(someComponent: MyComponent) {
    ...
}

This unfortunately results in the error:

'MyComponent' refers to a value, but is being used as a type here.

Something that works is this, where I create an instance and then use typeof of that instance in the function declaration:

const MyComponent = Vue.extend({...});

let myComponentInstance = new MyComponent();
function myFunction(someComponent: typeof myComponentInstance ) {
    ...
    someComponent.someProperty;
    ...
}

Is there a way to do this without having to create an instance of MyComponent? To me it feels like is should be possible as the knowledge is there.

Edit:

With the suggestion of @Bill-Naylor I got it down to this.

const MyComponent =  Vue.extend({
    data() {
        return {
            test: "test"
        }
    }
});

let dummy = () => new MyComponent();
export type MyComponentInstance = ReturnType<typeof dummy>

let test : MyComponentInstance;
let str = test.test;

Is it possible to get it down even more without the dummy function?

Edit2:

It is possible with InstanceType<...>.

This works:

const MyComponent =  Vue.extend({
    data() {
        return {
            test: "test"
        }
    }
});

export type MyComponentInstance = InstanceType<typeof MyComponent>

let test : MyComponentInstance;
let str = test.test;

Upvotes: 19

Views: 26817

Answers (1)

J. Vergeer
J. Vergeer

Reputation: 800

With the help of @BillNaylor who pointed me into the right direction I was able to find a solution.

I need to use InstanceType<...>

Example:

const MyComponent =  Vue.extend({
    data() {
        return {
            test: "test"
        }
    }
});

export type MyComponentInstance = InstanceType<typeof MyComponent>

let test : MyComponentInstance;
let str = test.test;

Upvotes: 36

Related Questions