Using TypeScript with Vue: Safely accessing component properties in a type-safe manner

I am currently exploring Vue's setup API and there is one aspect that I am struggling with: I need to retrieve properties of a child component from a parent component. Everything seems to be functioning correctly, but I am facing difficulties with the TypeScript definition. I keep encountering a TS error stating that the property does not exist. From a TypeScript standpoint, it appears to be accurate since the object I defined lacks the property. Nevertheless, I believe there must be a method to help TypeScript comprehend.

<template>
  <child ref="child" />
</template>

<script lang="ts">
import Child from 'child.vue'

export default {
  name: 'parent',
  mounted() {
    const child: Child = this.$refs.child;
    console.log(child.myprop); // TS2339: Property 'myprop' does not exist on type...
  }
}
</script>
<script lang="ts">
import {defineComponent} from 'vue';

export default defineComponent({
  name: 'child',
  setup(props, context) {
    const myprop = 1;
    context.expose({myprop});
    return {myprop};
  }
})
</script

Answer №1

Here are a couple of suggestions to try:

const instance: InstanceType<typeof Component> = this.$refs.component;

Alternatively, you can also use:

const instance = this.$refs.component as Component;

Answer №2

In this scenario, you have combined both the Composition API and Options API.

To streamline your code and enhance type handling, consider refactoring the parent component to utilize the Composition API:

import Child from 'child.vue'
    
export default {
  name: 'parent',
  setup() {
    const childRef = ref<InstanceType<typeof Child>>();

    onMounted(() => {
      console.log(childRef.value?.myProp);
    })

    return { childRef };
  }
}

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

Using v-model in Vue, the first option has been chosen

Is there a way to set a default value for myselect when a user visits the site for the first time? I want the first option to be selected initially, but allow the user to change their choice if they prefer another option. Can this be achieved using v-model ...

Developing a universal SDK wrapper for Firebase services (Firestore, Cloud Storage, and additional functionalities)

Currently, I am on the quest to discover an abstraction that can facilitate the seamless operation of Firebase products (specifically Firestore, Storage, and Analytics) across any platform (be it React Native, React, or Node.js). While considering the REST ...

What could be causing the error message "@vue/composition-api/dist/vue-composition-api.mjs Not Found" to appear every time I

I received a Vue.js project from my vendor and have downloaded all the necessary packages using npm install. However, when I attempt to run npm run dev, I consistently receive the following error message: This dependency was not found: @vue/composition-a ...

What are the TypeScript type definitions for the "package.json" configuration file?

What is the most efficient method for typing the content of the "package.json" file in TypeScript? import { promises as fs } from 'fs'; export function loadManifest(): Promise<any> { const manifestPath = `${PROJECT_DIR}/package.json`; ...

Guide on integrating msw with Next.js version 13.2.1 (Issue: Unable to access worker.start on the server)

I'm currently in the process of integrating a simulated API that sends back a response object containing a series of messages meant to be displayed in the UI (specifically, a chatbox) alongside the username, user picture, and other relevant informatio ...

Achieving endless image rotation using vue-kinesis

My current setup involves using vue-kinesis for animating an image. The component is functioning correctly, but the animation itself is being controlled through direct CSS. How can I adjust my configuration to have vue-kinesis handle the rotation instead? ...

How come the type checker is not throwing an error for this indexable type?

I recently delved into the Microsoft Typescript Handbook and found myself intrigued by the indexable types chapter. To gain a deeper understanding, I decided to experiment with the code provided. Strangely enough, upon running this particular piece of code ...

What strategies can I implement to safeguard against harmful Vuex mutations?

My Vue SPA quiz app utilizes a Vuex store to keep track of the number of correctly answered questions by users. This data is then transferred from the store to my server for storage in the database. However, I am concerned about the security risks. Is it ...

Issue in React Native and Firestore: The 'auth' property is not recognized in the specified type or an error object of unknown type

I am currently using Typescript in conjunction with Firebase and React Native. While working on the signup screen, I included Firebase like so: import * as firebase from 'firebase/app'; import 'firebase/auth'; In my onSignUp function, ...

This error occurred: "Property 'release' cannot be read because it is undefined."

Hello everyone! I'm in need of some assistance. I am trying to test my service tree with a specific structure. Here is an overview of my test: describe(`Service selector`, () => { describe(`getCurrentServiceTree`, () => { it(`should bui ...

Developing a TypeScript PureMVC project from scratch

Currently, I am working on a project to implement PureMVC in TypeScript using npm and grunt. Unfortunately, PureMVC has ended development on their project and there is a lack of resources for PureMVC in TypeScript online. The documentation only provides in ...

Error: The function $compile does not exist

Currently, I am working on developing an AngularJS directive using TypeScript. While testing my code in the browser, I encountered the following error: TypeError: $compile is not a function at compileComponent.js:14 Interestingly, the TypeScript compiler ...

Issue with Form Submit button functionality when applying conditional statement logic

Currently, I am working on implementing logic for a submit button that includes basic input validation to check for empty strings. However, when the button is clicked, the entire window clears out. I need to display one block based on meeting the condition ...

The animation for the accordion feature in the iOS Framework7-vue app seems to be moving at

I am encountering issues with the iOS app while developing both android and iOS apps with Framework7-vue. The Android app functions smoothly, but the iOS app is causing trouble. One of the features include a popup functionality with an accordion inside fo ...

Value binding with conditional rendering in VueJS 2

My goal is to utilize VueJS 2 to render an inline condition while simultaneously adding a value to a DOM element. I am aware that I can use v-if to control the visibility of elements based on conditions, but how can I achieve an inline condition? For exam ...

Suggestions for managing the window authentication popup in Protractor when working with Cucumber and TypeScript?

I'm a beginner with Protractor and I'm working on a script that needs to handle a window authentication pop-up when clicking on an element. I need to pass my user id and password to access the web page. Can someone guide me on how to handle this ...

I've come across certain challenges when setting values for Vue data objects

I'm having trouble with a Vue assignment. Here is my code: new Vue({ el: "#alarmEchartBar", data: { regusterUrl: Ohttp + "historicalAlarmRecord/chart", regDistrictUrl: Ohttp + "district", regStreetUrl: Ohttp + "street/", regCameraUrl: ...

Posting forms in NextJS can be optimized by utilizing onChange and keypress events for input fields

I am currently working on my first Edit/Update form within a newly created NextJs application as I am in the process of learning the framework. I seem to be facing an issue where the form constantly posts back to the server and causes the page to refresh ...

Anticipate that the typescript tsc will generate an error, yet no error was encountered

While working in the IDE to edit the TypeScript code, an issue was noticed in checkApp.ts with the following warning: Argument type { someWrongParams: any } is not assignable to parameter type AddAppToListParams. Surprisingly, when running tsc, no error ...

Using Vue to Pass Selected Value from Select Component to Another Component

Here is the template I am working with: <div class="container"> <div class="row"> <div class="col-lg-5 filter big"> <select v-model="stc" @change="getData" name= ...