2

I just switched from plain JavaScript to Typescript (or at least I'm trying to). Here is code that worked perfectly just before, minus the typing done so far:

<script lang="ts">
    import axios from 'axios';

    export default {
        name: "Index",
        data() {
            return {
                years: Array,
                bgs: Array
            }
        },
        methods: {
            loadYears: function (): void {
                let self = this;
                axios.get('../letter/get/years').then(function (response) {
                    function pushYears(value: any) {
                        self.years.push(value);

                    }

                    response.data['years'].forEach(pushYears);
                });
            },
            loadBg: function (): void {
                let self = this;
                axios.get('../bg/get/all').then(function (response) {
                    JSON.parse(response.data['bgs']).forEach(function (obj: any) {
                        self.bgs.push(obj);
                    })
                });
            }
        },
        beforeMount() {
            this.loadYears();
            this.loadBg();
        }
    }
</script>

now after switching to Typescript, self.years.push(value) and self.bgs.push(obj) are not working anymore, the corresponding errors says: "self.$data.years.push is not a function". Interestingly enough, in the beforeMount()-function I get an error saying that loadYears() and loadBg are not defined, but accessing the data()-objects works perfectly in this block via this.data().years or bgs. How can I access these properties inside my methods-block?

4
  • can you share your exact typescript code. Typescript in vue is quite a bit different than vanilla js Commented Mar 26, 2020 at 13:23
  • You basically saw everything, this is my whole <script>-Tag now Commented Mar 26, 2020 at 13:26
  • 1
    Use composition API. The syntax you're using isn't intended for easy typing. See vue-composition-api-rfc.netlify.com/api.html . bgs: Array - this is a mistake, this is not TS typing, you basically assign Array constructor, this is the reason why push is not a function. Commented Mar 26, 2020 at 13:31
  • see also vue typescript guide, it isn't a 1 to 1 transition from js to ts Commented Mar 26, 2020 at 13:48

1 Answer 1

2

you have two ways to type yours data properties as bellow:

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

interface Model {
  name: string
  age: number
}

export default Vue.extend({    
  data () {
    const foo: Model[] = [];
    return {
      foo,
      bar: [] as Model[]
    };
  },

  mounted () {
    this.foo.push({
      name: 'user', age: 22
    });
    this.bar.push({
      name: 'guest', age: 20
    });
  },
});
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.