Search code examples
typescriptvue.jsvuex

Using mapGetters in TypeScript and Vue


I can't find a straight answer on this and I'm not very good at TS. How can I convert these computed property in Vue to be used in a TypeScript file?

  computed: {
      ...mapGetters({
         getLoggedInUserFirstName: "Common/getLoggedInUserFirstName",
         getLoggedInUserLastName: "Common/getLoggedInUserLastName"
      })
  }

Solution

  • According to @LOTUSMS comments he said he is using inside a Vue file.

    Well, you have two options here. If you are using the class-based syntax a.k.a:

    @Component({})
    export default class MyComponent extends Vue {
      ...
    }
    

    you can do the following:

    @Component({
      computed: {
        ...mapGetters({
          getLoggedInUserFirstName: "Common/getLoggedInUserFirstName",
          getLoggedInUserLastName: "Common/getLoggedInUserLastName"
        })
      }
    })
    export default class MyComponent extends Vue {
      // if you can you can denote the type with:
      // public getLoggedInUserFirstName!: string;
      public getLoggedInUserFirstName!;
    
      public getLoggedInUserLastName!;
    }
    

    If you are using the extend version you can use it simplyly as you were using before:

    <script lang="ts">
    import Vue from 'vue';
    
    export default Vue.extend({
      computed: {
        ...mapGetters({
          getLoggedInUserFirstName: "Common/getLoggedInUserFirstName",
          getLoggedInUserLastName: "Common/getLoggedInUserLastName"
        })
      }
    })
    </script>