Skip to content
Advertisement

Vue 3 and Typescript – Cannot access data property in a method

Im trying to access my data in a method I am writing, but it does not seem to work. I get an TS2339 Typescript error saying that the property does not exist in the type.

TS2339: Property 'players' does not exist on type '{ onAddPlayers(): void; getPlayerPlaceholder(index: number): string; }'.   
    47 |   methods: {
    48 |     onAddPlayers() {
  > 49 |       this.games = prepareGames(this.players as PadelPlayer[]);
       |                                      ^^^^^^^
    50 |     },
    51 |     getPlayerPlaceholder(index: number) {
    52 |       const playerNumber = Number(index) + 1;

Here is the code for the component:

<script lang="ts">
import { PadelGame } from "@/models/padelGame.interface";
import { getPadelPlayers, prepareGames } from "../services/americanoService";
import { PadelPlayer } from "@/models/padelPlayer.interface";

const padelGames: PadelGame[] = [];

export default {
  data() {
    return {
      players: getPadelPlayers(),
      games: padelGames,
    };
  },
  methods: {
    onAddPlayers() {
      this.games = prepareGames(this.players as PadelPlayer[]);
    },
    getPlayerPlaceholder(index: number) {
      const playerNumber = Number(index) + 1;
      return "Spelare " + playerNumber;
    },
  },
};
</script>

Advertisement

Answer

to get types inference you should create component instance using defineComponent imported from vue:

<script lang="ts">
import { PadelGame } from "@/models/padelGame.interface";
import { getPadelPlayers, prepareGames } from "../services/americanoService";
import { PadelPlayer } from "@/models/padelPlayer.interface";
import {defineComponent} from 'vue'
const padelGames: PadelGame[] = [];

export default defineComponent({
  data() {
    return {
      players: getPadelPlayers(),
      games: padelGames,
    };
  },
  methods: {
    onAddPlayers() {
      this.games = prepareGames(this.players as PadelPlayer[]);
    },
    getPlayerPlaceholder(index: number) {
      const playerNumber = Number(index) + 1;
      return "Spelare " + playerNumber;
    },
  },
});
</script>
Advertisement