Encountering a "property does not exist" error while using VS Code TypeScript within a Vue.js project

I am working on a Vuejs project in Typescript. The project compiles and runs perfectly without any errors. However, I am facing an issue with the TS linter.

In my individual component files, I am using the component decorator as shown below:

//videocard.component.vue

<script lang="ts">
    import Vue from 'vue';
    import { Component, Prop } from 'vue-property-decorator';
    import { Video } from '../interfaces/video.interface';

    @Component
    export default class VideoCardComponent extends Vue {

        @Prop() readonly video: Video;
        @Prop() readonly loading: boolean;

        created(){
            console.log(this.static_url); // !COMPLAINS HERE!
        }

        get _video(){
            return this.video
        }

        get _loading(){
            return this.loading || false;
        }
    }
</script>

One thing to note is that when trying to log out a property called static_url, it works fine because I have set this property in my app.ts file like this:

//app.ts

Vue.prototype.static_url = (window as any).static_url;

I have added types so that static_url is recognized as a property on Vue, in a file like this:

// static_url.d.ts

import Vue from 'vue';

declare module 'vue/types/vue' {
    interface Vue {
      static_url: string;
    }

    interface VueConstructor {
      static_url: string
    }
}

The issue I'm facing is that Typescript does not recognize this property in the component files, even though it doesn't raise any complaints in the app.ts file. Why doesn't Typescript acknowledge this property in the component files?

Just for reference, here is the content of my tsconfig.json file:

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["esnext", "dom"],
        "strict": true,
        "module": "es2015",
        "noImplicitAny": false,
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "strictPropertyInitialization": false
    },
    "include": [
        "assets/js/video-app/src/**/*.ts",
        "assets/js/video-app/src/**/*.d.ts",
    ]
}

Answer №1

It seems like you are on the right track, but there could be an issue with the include statement in your tsconfig.json

Is it possible that your tsconfig.json is located outside of your project, causing the need for a assets/js/video-app/src path?

Typically, when the tsconfig.json is within the project, the include should be structured as follows to ensure proper functioning of custom type definitions:

"include": [
   "src/**/*.ts"
]

Have you confirmed whether static_url.d.ts is also contained within the src directory?

I have created a git repository to replicate your scenario, which you can compare against your current configurations.

Git Repository Link

Answer №2

If accuracy isn't a top priority here, you could try:

(this as any).static_url

However, if accuracy is crucial, I would advise against modifying the Vue prototype. It's not the cleanest practice in my opinion (I've had my fair share of headaches from dealing with projects where default object prototypes were cluttered with non-standard properties causing all sorts of bugs). If you're using a state management tool like Vuex, consider storing this data there instead.

Alternatively, if you want to avoid duplicating data between the window object and Vue.prototype, you can try:

(window as any).static_url

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

Guide to iterating through an Observable<Object[]> to generate an array of objects

Google Firestore collection named users is structured as follows : { "contactNumber":"0123456789", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e2e7e0e6ece7edc8efe5e9e1e4a6ebe ...

Load Angular component on demand with necessary dependencies

Searching for an elegant solution (without resorting to private APIs) to create a widget-style dashboard. The goal is to dynamically load components based on user role. Is there a way to import a component and its dependencies included in the component&ap ...

Implementing event dispatch on Push notifications received with Workbox

In my VueJS component, I have set up a listener for the pushMessageEvent event: <template> <div> <VueBotUI :options="options" :is-open="isOpen" :bot-typing="botTyping" :inpu ...

Ensuring that a date is within a certain format in TypeScript

Can someone help me verify the validity of different date formats? I attempted the following method: let newdate = new Date(myStringDate); Date.parse(myStringDate) result = `${newdate.getDate()}/${newdate.getMonth() + 1}/${newdate.getFullYear()}` The re ...

Is TypeScript's nullish coalescing operator (??) supported by more browsers compared to JavaScript's equivalent?

When it comes to the nullish coalescing operator (??) in JavaScript, browser support is limited to newer browsers such as Chrome 80, Edge 80, and Firefox 72. Since TypeScript gets converted to JavaScript, do nullish coalescing operators also undergo some ...

What is the best way to increase a JSON value in a Typescript scenario? For instance, how can I add more

Is there a way to update JSON values in a TypeScript example by incrementing likes or dislikes when a button is clicked?https://i.sstatic.net/aon03.png movies: any[] = [ { name: "Fan", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/fan.jpg" }, ...

The Safari keyboard navigation feature suddenly disappeared after uploading to Google App Engine

My current website is built using Vue.js (2.x) and deployed on Google App Engine. After testing the deployed application in Safari, I noticed that the accessibility feature "'skip navigation' on :focus" was no longer functioning proper ...

Issue during Docker build: npm WARN EBADENGINE Detected unsupported engine version

Currently, I am constructing an image based on mcr.microsoft.com/devcontainers/python:0-3.11-bullseye. In my docker file, I have included the following commands towards the end: RUN apt-get update && apt-get install -y nodejs npm RUN npm install np ...

Getting the value of a nested object in Vuejs using Laravel

I am currently working with Laravel 8 and integrating the Laravel Spatie package for managing roles and permissions. My goal is to retrieve all admin users along with their respective roles and pass this information to vuejs. $users = Admin::orderBy(' ...

Can't get className to work in VueJS function

I need help changing the classNames of elements with the "link" class. When I call a method via a click action, I can successfully get the length of the elements, but adding a class does not seem to work. Does anyone have any insights into this issue? HTM ...

The SupabaseAuthClient type does not have a property named 'session' available

Here is the complete code snippet for page.tsx: "use client"; import React, { useState, useEffect } from "react"; import axios from "axios"; import { Session } from "@supabase/supabase-js"; import { Auth } from " ...

Switch out the Jquery modal trigger for VueJS

Currently learning Vue.js and attempting to convert a Jquery call to Vue.js. Hopefully, it's a straightforward process? Recently integrated the bootstrap-vue library with hopes of replacing the usage of JQuery. Interested in migrating the following ...

After being initialized, the added Vue.js DOM elements do not function together

I updated an HTML page with ajax contents and incorporated Vue.js for front-end events. Unfortunately, the dynamically added elements are not interacting with the Vue.js instance, even when I attempted to forceUpdate them. Any suggestions on how to resol ...

Limit class generic to specify constructor argument type

I have a unique object that I need to transform into various structures based on its keys. Each key-value pair must be treated individually, so I intend to convert the object into an array of entries, then map those entries into policy objects and finally ...

Issues encountered while attempting to convert HTML Image and Canvas Tags to PDF within Angular 2

I am currently facing an issue with my code. My requirement is to download HTML content as a PDF file. I have been successful in downloading text elements like the <p> tag, but I am encountering difficulties when trying to download images and canvas ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

Executing Function when Vue JS Input Loses Focus

Hey there, I have a quick question regarding Vue JS. So, on my website, I have a shopping cart feature where users can enter any quantity. The issue I'm facing is that every time a user types a digit in the input field, the save method gets triggered. ...

Getting a `undefined` value when changing templates in VueJS

Currently, I am transitioning a list to a table to enable more columns in the future, but I have encountered an undefined variable error that has left me confused. Below is the original list: <ul class="collection with-header"> ...

Setting the axios baseURL configuration globally in Nuxt.js

When starting a new project, you can use the following command: npm init nuxt-app <project-name> To set up the baseURL for axios, refer to this guide: npm install @nuxtjs/axios In your nuxt.config.js file: modules: [ '@nuxtjs/axios' ...