I'm currently developing a vuejs application using typescript and my goal is to leverage the available typings as much as possible.
For the most part, the typings and type inference work smoothly without any issues.
However, in certain parts of my code, I'd like to pass a reference to a specific component type, like this:
const MyComponent = Vue.extend({...});
function myFunction(someComponent: MyComponent) {
...
}
Unfortunately, this approach leads to an error:
'MyComponent' refers to a value, but is being used as a type here.
One workaround that seems to work is creating an instance and using 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 achieve this without the need to create an instance of MyComponent
? It seems like it should be feasible given the existing knowledge.
Edit:
Following the suggestion by @Bill-Naylor, I was able to simplify it 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 there a way to further streamline this without the use of the dummy function?
Edit2:
It turns out that it can be achieved with InstanceType<...>
.
This solution works:
const MyComponent = Vue.extend({
data() {
return {
test: "test"
}
}
});
export type MyComponentInstance = InstanceType<typeof MyComponent>
let test : MyComponentInstance;
let str = test.test;