The error message "Vue CLI 3 typescript - Property 'x' does not exist on type 'Vue'" indicates that the 'x' property is not recognized

Encountering a strange error that is puzzling. The error message indicates that isGenre is not recognized as a property of type Vue, even though isGenre is clearly defined as a computed property.

<script lang="ts">
import Vue from 'vue'

import { WIDTH_TWO_ICONS } from '@/const/tables-style'

export default Vue.extend({
    props: {
        list: Array,
        listType: String
    },
    data: () => ({ WIDTH_TWO_ICONS }),
    computed: {
        isGenre(): boolean {
            return this.listType === 'genre'
        },
        isMood(): boolean {
            return this.listType === 'mood'
        }
    },
    methods: {
        routerLink(paramsId: number): object {
            return { name: 'GenreOrMoodEdit', params: { id: paramsId }, query: { type: this.isGenre ? 'genre' : 'mood' } }
        }
    }
})
</script>

Error Report

59:93 Property 'isGenre' does not exist on type 'Vue'.
    57 |     methods: {
    58 |         routerLink(paramsId: number): object {
  > 59 |             return { name: 'GenreOrMoodEdit', params: { id: paramsId }, query: { type: this.isGenre ? 'genre' : 'mood' } }
       |                                                                                             ^
    60 |         }
    61 |     }
    62 | })

Main.ts

declare module 'vue/types/vue' {
    // Global properties can be declared
    // on the `VueConstructor` interface
    interface VueConstructor {
        $axios: any
        router: any
    }
    interface Vue {
        $axios: any
        router: any
    }
}

import Vue from 'vue'
import App from './App.vue'
import router from '@/router'
import store from '@/store'
import './registerServiceWorker'
import '@/plugins'
import '@/directives'

import '@/sass/main.sass'

Vue.config.productionTip = false

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')

Tsconfig.js

{
    "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "strict": true,
        "jsx": "preserve",
        "importHelpers": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "sourceMap": true,
        "strictNullChecks": false,
        "baseUrl": ".",
        "types": ["node", "mocha", "chai"],
        "paths": {
            "@/*": ["src/*"]
        },
        "lib": ["esnext", "dom", "dom.iterable", "scripthost"]
    },
    "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx"],
    "exclude": ["node_modules"],
    "files": ["src/interfaces/*"]
}

Tslint.js

{
    "defaultSeverity": "warning",
    "extends": ["tslint:recommended"],
    "linterOptions": {
        "exclude": ["node_modules/**", "./src/assets/icons/*"]
    },
    "rules": {
        "quotemark": [true, "single", "avoid-escape"],
        "arrow-parens": false,
        "semicolon": false,
        "object-literal-sort-keys": false,
        "max-line-length": [true, 160],
        "ordered-imports": false,
        "interface-name": false,
        "trailing-comma": false,
        "no-unused-expression": true,
        "object-literal-shorthand": false,
        "curly": false,
        "no-console": false
    }
}

Answer №1

The issue lies in how you have specified the list prop as an Array.

In reality, Array is just a synonym for the ArrayConstructor type.

https://i.sstatic.net/aKkBN.png

The ArrayConstructor constructor actually returns Array<any>, which is not the same as ArrayConstructor.

Solution:

You should create an interface specifically for the list property.

For example:

The list should be an array of items called Item.

interface Item { ... }

At that point, cast the Array to a function that will return the interface.

props: {
  list: Array as () => Item[],
}

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

How can I implement a feature that allows toggling visibility for multiple password fields within a dynamic form using Vuetify in Vue.js?

I am currently working with a dynamic form that is generated based on JSON data from the backend, including input types, IDs, names, and values. In one of my forms, there are two password fields sourced from the backend. I'm trying to find a way to to ...

Secure Socket Layer (SSL) certification for hosting an HTTP server on an

I am currently facing an issue with insecure SSL certificates within my project that consists of two main components: An ESP32 IoT device with a HTTPS server A VUE2 + Vuetify PWA web application deployed on Firebase hosting. Imagine a scenario where a c ...

How to transition from using a CDN to NPM for implementing the Google Maps JavaScript MarkerClusterer?

Currently integrating Google Maps JavaScript MarkerClusterer from CDN, I am considering transitioning to the NPM version for Typescript checking in my JavaScript files. However, I am encountering difficulties understanding how to make this switch. The docu ...

Enhance precision with autofocus feature while utilizing Quasar's Q-Field validation

Currently, I am in the process of setting up a form using Quasar and implementing internal validation. The specific issue I am facing involves a group of checkboxes where the user must select at least one option. While I have successfully implemented the v ...

When you hit the refresh button, the vue router automatically redirects you back to

I've encountered an issue with my vuejs project involving the use of vue router in a single page application. While I am able to navigate to different pages using vue router, whenever I reload the page at any route, it ends up redirecting me back to t ...

The first click causes Highchart to display with varying heights

I have implemented a highchart within a chart object in HTML, with CSS defining the height and width of the chart object. Initially, upon first render, the chart has a height of 290px. However, when I click on the tab again, the chart stretches to a height ...

Creating a union type from an array that is not a literal (using `Object.keys` and `Array.map`)

Can a union be derived from a non-literal array? I attempted the following: const tokens = { "--prefix-apple": "apple", "--prefix-orange": "orange" }; const tokenNames = Object.keys(tokens).map(token => toke ...

What defines the category of a component in Angular 13?

As I work on creating a component that accepts another component as an input, I encountered a situation where I needed to define the input type correctly. You can check out a demo of this in action here on StackBlitz. In the @Input() section of the ParentC ...

"Unlock the power of vue i18n pluralization with these step-by-step instructions

Below are some locale messages I have: timing: { viewer: { count: 'нету таймингов | 1 тайминг | 2 тайминга | 3 тайминга | 4 тайминга | {count} таймингов' } } Here is my template: < ...

What steps should I take to resolve the Heroku TypeScript and Node.js build error I'm experiencing?

This is my first time using Heroku. I encountered multiple errors in the Heroku logs when trying to deploy my project: 2023-02-03T09:02:57.853394+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=tech- ...

What is the best way to transfer my static files to the desired output directory in a TypeScript Express application?

I am attempting to transfer my static files from the input directory to the output directory using Express. I found guidance in this tutorial, which utilized shell.js for copying static files. The code responsible for this operation is located in CopyAsse ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

Tips for resolving the setAttribute() function error message: "Argument of type 'boolean' is not assignable to parameter of type 'string'"

I am currently working on a function that dynamically updates the HTML aria-expanded attribute based on whether it is true or false. However, when I declare element as HTMLElement, I encounter an error stating Argument of type 'boolean' is not as ...

Generating statically typed events in Vue

Recently, I encountered a run-time error in a Vue / Typescript application due to the lack of typing for custom events. For example, the following code compiles without any issues but fails at run-time: // Within component A public foo() { this.$e ...

When developing in vue.js and preparing for production, I encounter a 404 error with certain files located within the static folder, despite the fact that the URLs are accurate

As I prepare my application for production, I have encountered an issue. While everything works perfectly in the development environment, upon building and uploading the application to the server, only the HTML, Javascript, some CSS, and a few files load. ...

Can Enums be nested in Typescript?

Consider the following enums: export enum Category { FOOD = 'food', DRINK = 'drink' } export enum Type { COLD = 'cold', HOT = 'hot' } Can these be combined into a single enum? For example: export enum Prod ...

What are the steps to enable generators support in TypeScript 1.6 using Visual Studio Code?

I have been working with ES6 in Visual Studio Code for some time now, but when I attempt to transition to TypeScript, I encounter errors like: Generators are only available when targeting ECMAScript 6 Even though my tsconfig.json file specifies the ES6 ...

`Incredible sequence of events unfolding`

In order to add an additional action after the deletion process is complete, I must make modifications to an epic. The current epic code is as follows: const deleteComponentEpic: Epic< AppActions, AppActions, AppStore, ComponentDetailsEpicsDepen ...

Angular's interactive checkboxes and dropdown menus provide a dynamic user experience

There is a global List array where data from an API is passed in the OnInit method. List: any; visibility:any; Status:any; ngOnInit(): void { let param = {...}; this.Service.getUser(param).subscribe(result => { this.List = result['response ...

Guide to resolving Vue 2 and UIKit autocomplete template issues

I am encountering an issue with the Vue 2 + UIKit autocomplete feature. The template for the UIKit autocomplete is shown in the following code: <script type="text/autocomplete" v-pre> <ul class="uk-nav uk-nav-autocomplete uk-autocomplete-res ...