Search code examples
typescriptvue.jsionic-frameworkvuejs3ionic5

TS2339: Property 'posts' does not exist on type


This is my code where I try to call API in ionic 5 with Axios

import axios from "axios";

import {
  IonCard,
  IonCardContent,
  IonCardSubtitle,
  IonCardTitle
} from "@ionic/vue";

export default {
  name: "Tab1",
  components: {
    IonCard,
    IonCardContent,
    IonCardSubtitle,
    IonCardTitle
  },
  data() {
    return { posts: [] };
  },

  created() {
    axios.get("http://gautammenaria.com/wp-json/wp/v2/posts").then(response => {
      this.posts = response.data;
    });
  }
};

Get this error (Also get data as expected )

TS2339: Property 'posts' does not exist on type '{ name: string; components: {

Not sure what it is


Solution

  • You should build your component using defineComponent function to get types inference :

    import axios from "axios";
    
    import {
      IonCard,
      IonCardContent,
      IonCardSubtitle,
      IonCardTitle
    } from "@ionic/vue";
    
    import {defineComponent} from 'vue'
    
    export default defineComponent({
      name: "Tab1",
      components: {
        IonCard,
        IonCardContent,
        IonCardSubtitle,
        IonCardTitle
      },
      data() {
        return { posts: [] };
      },
    
      created() {
        axios.get("http://gautammenaria.com/wp-json/wp/v2/posts").then(response => {
          this.posts = response.data;
        });
      }
    });