Vue component prop values are not properly recognized by Typescript

Below is a Vue component I have created for a generic sidebar that can be used multiple times with different data:

<template>
    <div>
        <h5>{{ title }}</h5>
        <div v-for="prop of data" :key="prop.id">
            <router-link :to="path(prop.id)">{{ prop.name }}
            <i class="material-icons right">edit</i></router-link>
        </div>
    </div>
</template>

<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
    props: {
        data: Array,
        title: String,
        pathbase: String
    },
    methods: {
        path(id): string {
            return `${this.$props.pathbase}/${id}`;
        }
    }
});
</script>

My question pertains to the use of this.$props.pathbase as opposed to just this.pathbase. Why does Typescript consider this.pathbase as "invalid" when accessing the prop? Although my project compiles and functions correctly, TypeScript in VSCode raises an error message stating:

Property 'pathbase' does not exist on type 'Vue'.

I am curious about this discrepancy and would like to gain a deeper understanding. Why does Typescript require the use of $props even if the code runs without issue? What is the reason behind its insistence on using $props? It's puzzling why this.pathbase triggers a Typescript complaint despite being manageable by Vue during compilation.

Answer №1

Typically, the use of $props is not required. The issue at hand resembles a known problem with Vue and TypeScript, where TypeScript's inference for all props is lost when one of them has the type {}. However, in this case, the issue arises from having a prop with the type Array (i.e., data: Array) which leads to the same complication, hindering access to this.pathbase.

The solution is to define the type Array as as () => Foo[] (or as PropType<Foo[]> for version 2.6 onwards), with Foo representing the expected type of each item in data:

import Vue from 'vue'

export default new Vue.extend({
  props: {
    data: Array as () => string[],
  }
})

OR:

// PropType added in version 2.6
import Vue, { PropType } from 'vue'

export default new Vue.extend({
  props: {
    data: Array as PropType<string[]>,
  }
})

https://i.stack.imgur.com/pa5Yr.gif


UPDATE This issue was addressed in Vue version 2.6.0.

Answer №2

When it comes to props, remember that they are read-only in React. This means that the child component cannot modify the data passed down from its parent. Take 'Pathbase' for example - it's a property in your props object and to access it, you must use 'this.props'.

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

Vue.js app does not have the capability to display JSON data as a table

I successfully fetched JSON data in my vue app from the endpoint '/v1/api/sse?raceId=1', but I'm struggling to convert this JSON into a table format. The JSON is displaying correctly, but I'm unsure how to structure it into a table. He ...

I'm having trouble inputting text into my applications using React.js and TypeScript

I am encountering an issue where I am unable to enter text in the input fields even though my code seems correct. Can anyone help me figure out what might be causing this problem? Below is the code snippet that I am referring to: const Login: SFC<LoginP ...

I'm struggling to find a solution to this pesky TypeScript error that keeps popping up in the button component's styling. How can

An error related to style is appearing: <Button style = No overload matches this call. Overload 1 of 3, '(props: { href : string; } & { children?: React Node; classes?: Partial<Button Classes> | undefined; color?: "primary" | ...

Script CSP was declined from loading

After implementing CSP on my Nuxt website successfully, I encountered an issue when I added addMeta:true to the CSP object. This resulted in the following error message: https://i.sstatic.net/H5eTn.png Error message received: Refused to load the script ...

Is it possible for an object to be undefined in NextJS Typescript even after using a guard

Hey there, I could really use some help with a React component I'm working on. This is one of my initial projects and I've encountered an issue involving fetching async data. Below is the current state of my solution: import { Component } from &q ...

Using TypeScript to Add Items to a Sorted Set in Redis

When attempting to insert a value into a sorted set in Redis using TypeScript with code like client.ZADD('test', 10, 'test'), an error is thrown Error: Argument of type '["test", 10, "test"]' is not assigna ...

`The flaw in filtering logic - an analysis`

Looking to find matching records within two Lists. We have a List called allAnimals with attributes like animalId, and another List named domesticAnimals also containing animalId. The goal is to compare the two lists and create a new list where the anima ...

The TypeScript factory class anticipates an intersection

In my code, I have a class factory called pickSomething that generates a specific type based on a key provided from a ClassMap: class A { keya = "a" as const; } class B { keyb = "b" as const; } type ClassMap = { a: A b: B } c ...

Firebase: Database and Storage - the art of efficiently linking images to posts | Vue.js

React Redux MongoDB I have developed a platform for users to share text and an image with their posts. Currently, I am assigning the complete URL of the image associated with each post using post.postPicture. This method is functional. The images are sav ...

Error in vue3 with typescript: unable to assign a ComputeRef<number[]> argument to an iterable<number> in d3.js

This code snippet was originally sourced from an example at https://medium.com/@lambrospd/5-simple-rules-to-data-visualization-with-vue-js-and-d3-js-f6b2bd6a1d40 I attempted to adapt the example to a TypeScript/Vue 3 version, and below is my implementatio ...

Issues with reactivity are present in certain items within Vue.js cards

Can someone please assist me with this issue that has been causing me trouble for days? I am working on updating the quantity and total price in a checkout card: The parent component: <template> <div> <upsell-checkout-product ...

Do Not Replace Bootstrap Theming

Good day, I am encountering an issue that has left me puzzled. I am attempting to modify the color scheme of bootstrap using SCSS in my Vue project, but it seems to be ineffective when I execute npm run serve. Below are snippets from my files: custom_boo ...

Guide to implementing c3 library in vue.js

I've been attempting to use c3 from the c3 site, but it's not working, here is my code within the template <vue-c3 :handler="handler"></vue-c3> then in the script <script> import VueC3 from 'vue-c3' export default ...

Discovering specific values for an ID using API calls in Angular (Implementing CRUD Operations in Angular with API Integration)

My current project involves CRUD operations in Angular utilizing the API created in Laravel. I have successfully added and fetched values, but encountered an issue when attempting to update values using their respective IDs. This snippet is from my app.co ...

The react-bootstrap module does not have any members available for export

I'm looking to incorporate the npm module react-bootstrap from this link into my Layout component, following the ASP.NET Core 2.1 template client project structure. The challenge I'm facing is that the template uses a .js file extension, but I pr ...

Utilizing VUETIFY DataTable: Implementing v-if in table header to conceal specific columns from users

I need to restrict access to the action for non-admin users. To accomplish this, I'm utilizing a data-table. Below is the code snippet I'm using: <v-data-table dense :headers="stampedDocumentsHeaders" :items="filterCutOffA ...

Create a checklist with unique identification, value, and description by utilizing an array of objects

Utilizing React with Typescript, I am tasked with constructing the React component MultiSelectCheckBoxes by supplying an array of Objects of type Color to the constructor: The structure for a checkbox list should be like this: const options = [{ "id": ...

What is the best way to exclude multiple properties from an object in JavaScript?

Having two methods that return Pick<T, K> and Omit<T, K> types where Omit is defined as type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>, I am facing difficulty in removing multiple properties from an object. Th ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

Container that has the ability to store objects conforming to specific interfaces

If you were to envision having three different types of objects, they might look something like this: interface X { testX: someType; } interface Y { testY: someOtherType[]; } interface Z { testZ1: string; testZ2: number; } Now imagine a master o ...