Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript / Vuejs not compiling for computed property

I'm starting to learn typescript & Vuejs.

Can anyone explain me why I can't access the account property in data from the computed allChecked()?

import * as Vue from "vue";

declare var accounts: any[];    

var app = new Vue({
    el: '#vueowner',
    data: {
        accounts: accounts,
        hasAccount: this.accounts.length > 0,
        checkedAccounts: []
    },
    computed: {
        allChecked() {
            return this.accounts.length === this.checkedAccounts.length;
        }
    }
})

I have this errors

ERROR in index.ts
(25,25): error TS2339: Property 'accounts' does not exist on type 'Vue'.

ERROR in index.ts
(25,50): error TS2339: Property 'checkedAccounts' does not exist on type 'Vue'.
like image 378
JuChom Avatar asked Jun 20 '17 13:06

JuChom


People also ask

Is computed property reactive in Vue?

The Basics of Vue Reactivity Simply put, a computed property's dependencies are the reactive values that help the property that determine the value that is returned. If none of these change, then, again, the cached value will be returned. If no reactive dependency is changed, a computed property is not recalculated.

Can you call a computed function Vuejs?

You can call a method from computed properties or watchers.

What is the difference between watchers and computed property in Vuejs?

Computed properties are used to calculate the value of a property based on some other conditions. Watchers, on the other hand, are not primarily used for changing the value of a property; instead, they are used to notify you when the value has changed and let you perform certain actions based on these changes.

Can we use TypeScript in Vuejs?

Now that Vue officially supports TypeScript, it's easy to create TypeScript projects from scratch using only the Vue CLI without any third-party libraries.


2 Answers

Looks like you need to annotate the return types because TypeScript has difficulties inferring the types of certain methods.

so instead of

allChecked() {
   return this.accounts.length === this.checkedAccounts.length;
}

try this

allChecked(): boolean {
   return this.accounts.length === this.checkedAccounts.length;
}
like image 146
RMcfarlane Avatar answered Nov 05 '22 02:11

RMcfarlane


In your allChecked method the this keyword isn't referencing the option object you are passing to the Vueconstructor, but the instance of the Vue class itself.

You will need to create a class that extends Vue with the properties you wish to add to the original class :

import * as Vue from "vue";

class MyVue extends Vue {
    accounts: any[];
    checkedAccounts: any[];
}

const app = new MyVue({
    // (...)
})

If you need more information about using Vue.js with Typescript check out this page: https://vuejs.org/v2/guide/typescript.html

like image 36
Lyrkan Avatar answered Nov 05 '22 02:11

Lyrkan