How can I determine the type of a component in Vue.js?

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;

Answer №1

I received guidance from @BillNaylor which led me to the solution I was seeking.

The key is to utilize InstanceType<...>

Here's an example:

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

export type MyComponentInstance = InstanceType<typeof MyComponent>

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Break down the table output based on column values with Vue

At the moment, my data is being displayed in one table. https://i.sstatic.net/C1mmY.png What I am looking to achieve is having a separate table for each code. For example, all instances of Code 1 should be in one table, Code 2 in another table, and so on ...

Ways to troubleshoot opencv.js generating random values when applying cv.threshold

Whenever I choose an image and use cv.threshold, it outputs a strange number 6620912 The number seems to change at times https://i.sstatic.net/Tp9LP.png 6620912 Promise.catch (async) (anonymous) @ App.tsx:49 commitHookEffectListMount @ react-dom_client ...

The async/await feature in Typescript fails to trigger updates in the AngularJS view

Currently, I am utilizing Typescript 2.1 (developer version) to transpile async/await to ES5. An issue I have encountered is that when I modify any property linked to the view within my async function, the view does not automatically reflect the updated v ...

The custom declaration file for the 'react-dates' module could not be located

I've been struggling to create a custom declaration file for the 'react-dates' npm package, but I'm facing issues with the compiler not recognizing my declaration file. Whenever I try to import DateRangePicker from 'react-dates&ap ...

Vue: auto-suggest feature in a text input field

I am looking to implement a text field with typeahead functionality. Essentially, I have a collection of words and as you start typing in the field, suggestions should appear based on the input. The challenge is that it should be capable of providing sugge ...

What is the best way to import a typescript file using a provided string?

I have a directory filled with JSON schemas, all coded in TypeScript. My goal is to import them collectively while preserving the typing, instead of having to write out numerous import statements. These schemas are utilized for validating JSON data being ...

Storing JSON data using Vuex

As I am delving into the world of Vuex store used with vue.js, I find myself wanting to implement it in a specific scenario. 1. Is STATE referring to any data, whether static or dynamic, that is provided by the server or stored in a JSON format? TEMPLATE ...

Exploring fresh opportunities within the Electron Vue.js application using router hash mode

When working on my Electron Vue.js application, I found the need to incorporate multiple windows, similar to modals on a website. To manage these windows/modals effectively, I created a service within my application. Initially, during the app development ...

Looking to pass two distinct variables using a single props with v-if in Vue-JS. Any suggestions?

I am attempting to pass different data to my other component. Essentially, when my variable firstvalue is not null, I want to send firstvalue. Currently, this setup is functioning as expected. However, I now wish to send secondvalue if it is not null. < ...

Displaying HTML in Vue using Ionic4: A Quick Tutorial

Exploring the features of Ionic_beta combined with Vue. One interesting observation: when a <div> containing HTML is placed within an <ion-content> directive in a component template, the HTML does not display. However, if the <ion-content& ...

Exploring the power of Vue CLI service in conjunction with TypeScript

I've recently set up a Vue project using the Vue CLI, but now I am looking to incorporate TypeScript into it. While exploring options, I came across this helpful guide. However, it suggests adding a Webpack configuration and replacing vue-cli-service ...

The parameter does not accept a string as an argument, it only allows for values of "one", "two", "three", "four", "five", or "six"

I'm facing a challenge with my specific type: type OtpCode = { one: string; two: string; three: string; four: string; five: string; six: string; }; I want to iterate through this object and assign values: Object.keys(defaultValues).forEac ...

The dropdown in vue-multiselect automatically closes after the first selection is made, ensuring a smooth user experience. However,

I am experiencing an issue where the dropdown closes after the first selection, despite setting close-on-select="false". However, it works properly after the initial select. You can observe this behavior directly on the homepage at the following link: vue ...

Checking if a function gets invoked upon the mounting of a component

I've been working on testing a method call when a component is mounted, but I keep encountering an issue: The mock function was expected to be called once, but it wasn't called at all. Here's the code snippet for the component: <templ ...

Ensuring Proper Implementation of Tailwind CSS Styles on Next.js Image Component with Relative Positioning

Having some challenges while attempting to integrate the Next.js Image component into my React project alongside Tailwind CSS. Specifically, I'm facing issues with applying relative positioning and other styles like objectFit. It seems that the root c ...

Utilizing Loadash for Sorting in VueJs

I am currently utilizing lodash's sortBy function in my code. Below is how it looks: import { sortBy } from 'lodash.sortby'; computed: { visibleInsights() { return sortBy(this.insights.filter(insight => { const id = thi ...

The name of the OpenLayers geometry is not preserved upon loading from WFS

While using OpenLayers 6 and GeoServer 2.16 (with PostGIS), I encountered a problem where the geometry name of loaded layers from GeoServer gets overwritten. In GeoServer, the geometry name (and column in PostGIS) is defined as geom. The XML response from ...

I am experiencing an issue where the scrolling behavior in Ionic Vuejs does not move upwards

Developing with Ionic 6 and the latest version of Vuejs, Vuejs 3 const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes, scrollBehavior(to, from, savedPosition) { return savedPosition || { top: 0 } }, ...

How can I retrieve the text input from a physical barcode scanner in a React Native screen?

Currently, I am developing a mobile application with React Native version 0.68.2. I am seeking a solution to detect barcode scanning events from a physical scanner hardware that is integrated into the mobile device as a handheld scanner. The key requirem ...

Tips for transferring variables between two browser windows within the same session of Internet Explorer 11

Is there a way to prevent a parameter from displaying in the address bar and avoid storing it locally? For example, the parameter value is like vndfj/dfgdgdfg12/dg==. I attempted the following code, but it does not work on IE and Edge browsers: let data ...