Search code examples
typescriptvue.jsvuejs2vuex

VueJS String interpolation can access private attribute of TS object


Hi I recently start to learn vuejs by using typescript I made a model class using typescript and in it there are private attributes that need supposedly can only be accessed via getters and put it in vuex store

But in the string interpolation (moustache), somehow I can get the private attributes without getter

Please look at my code below, Thanks!

User.ts

import { Stock } from "./Stock";

export class User {
  private _funds: number;
  private _portofolio: Array<Stock>;

  constructor() {
    this._funds = 5000;
    this._portofolio = [];
  }
  public updateFunds(by: number): void {
    this._funds += by;
  }
  get portofolio(): Array<Stock> {
    return this._portofolio;
  }
}

store/index.ts (vuex load)

import Vue from "vue";
import Vuex from "vuex";
import { User } from "@/models/User";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: new User()
  },
  getters: {
    currentUser: state => {
      return state.user;
    }
  },
  mutations: {},
  actions: {},
  modules: {}
});

App.vue (Master vue file)


<template>
  <div id="app">
        <p>Funds: {{ user._funds }}</p>
  </div>
</template>

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

export default Vue.extend({
  data: function() {
    return {
      user: this.$store.getters.currentUser
    };
  },
  created: function() {
    console.log(this.user);
  }
});
</script>


Solution

  • TypeScript private members can be freely accessed at runtime. That they are underscored allows to distinguish them from public members. If they aren't supposed to be accessed, don't access them. This can be prohibited for a team with a style guide.

    TypeScript visibility is checked at compilation time. Vue loader doesn't provide TypeScript support for templates. There's vue-type-check third-party utility that provides TS type checks for templates.