What is the root cause of the error "Property does not exist on type ObjectConstructor" occurring within this Vue 3 application?

Building an SPA using Vue 3, TypeScript, and The Movie Database (TMDB) API has been my latest project. In order to differentiate the movie score "bubble" with different styles, I have utilized the computed property movieQuality.

To achieve this, within src\components\MovieDetails.vue, I have included:

<template>
  <div class="row">
    <div class="col-sm-4 col-md-3">
      <div class="poster-container text-center text-sm-start my-3">
        <img
          :src="`https://image.tmdb.org/t/p/w600_and_h900_bestv2/${movie.poster_path}`"
          :alt="movie.title"
          class="img-fluid shadow-sm"
        />
      </div>

      <div class="user-score">
        <strong>User Score:</strong>
        <span class="score" :class="{ good: isGood, average: isAverage , bad: isBad }">{{
          Number(movie.vote_average).toFixed(2)
        }}</span>
      </div>
    </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import env from "../env";
import TrailerCarousel from "./TrailerCarousel.vue";
import ActorCard from "./ActorCard.vue";

export default defineComponent({
  name: "MovieDetails",

  components: {
    TrailerCarousel,
    ActorCard,
  },

  data() {
    return {
      route: useRoute(),
      movie: Object,
      movieTrailers: [],
      movieCast: [],
    };
  },

  mounted() {
    this.getMovieDetails();
  },

  methods: {
    getMovieDetails() {
      axios
        .get(
          `${env.api_url}/movie/${this.route.params.id}?api_key=${env.api_key}`
        )
        .then((response) => {
          this.movie = response.data;
        })
        .catch((err) => console.log(err));
    },

    // More code, not relevant to the question

    computed: {
      movieQuality() {
        switch(true) {
          case Number(this.movie.vote_average) <= 6:
            return 'bad'
            break;
          case Number(this.movie.vote_average) > 6 && Number(this.movie.vote_average) < 7.5:
            return 'average'
            break;
          default:
            return 'good'
        }
      }
    }
  });
</script>

<style scoped lang="scss">

.user-score {
  display: flex;
  align-items: center;

  .score {
    width: 30px;
    height: 30px;
    margin-left: 5px;
    border-radius: 50%;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1);
    font-size: 11px;
    line-height: 1;
    font-weight: 500;
    display: flex;
    justify-content: center;
    align-items: center;

    &.good {
      background: #0b8a52;
      color: #fff;
    }

    &.average {
      background: #f7ff1d;
      color: #222;
    }

    &.bad {
      background: #ff1d30;
      color: #fff;
    }
  }
}
</style>

Latest Update

A new "model" has been created in src\models\Movie.ts:

export class Movie {
    id?: number;
    adult?: boolean;
    backdrop_path?: string;
    poster_path?: string;
    title?: string;
    tagline?: string;
    overview?: string;
    genres?: any;
    original_title?: string;
    release_date?: string;
    runtime?: number;
    vote_average?: string;
}

It is imported into the component like so:

import { Movie } from "../models/Movie";

and implemented as follows:

data() {
    return {
      route: useRoute(),
      movie: Movie, // Utilizing the model now
      movieTrailers: [],
      movieCast: [],
    };
},

Stackblitz Demo

A live demo of the project can be accessed on Stackblitz via HERE.

The Issue at Hand

Despite Evan believing that the vote_average property exists within the movie object, the movieQuality() function throws an error:

Property 'vote_average' does not exist on type 'ObjectConstructor'.

Queries

  1. In what way am I overlooking things?
  2. What is the most effective approach to rectify this concern?

Answer №1

Avoid using classes for data typing.

Classes serve as blueprints for creating object instances. To define their structures, it's recommended to utilize interfaces and/or types.

To sum up, make this adjustment:

export class Movie {
    id?: number;
    adult?: boolean;
    backdrop_path?: string;
    poster_path?: string;
    title?: string;
    tagline?: string;
    overview?: string;
    genre_ids?: any;
    original_title?: string;
    release_date?: string;
    runtime?: number;
    vote_average?: string;
}

...to this:

export interface Movie {
    id?: number;
    adult?: boolean;
    backdrop_path?: string;
    poster_path?: string;
    title?: string;
    tagline?: string;
    overview?: string;
    genre_ids?: any;
    original_title?: string;
    release_date?: string;
    runtime?: number;
    vote_average?: string;
}

Once you've made the update, you're all set to proceed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The impact of redefining TypeScript constructor parameter properties when inheriting classes

Exploring the inner workings of TypeScript from a more theoretical perspective. Referencing this particular discussion and drawing from personal experiences, it appears that there are two distinct methods for handling constructor parameter properties when ...

Embedding in webpack compilation

My current setup involves using webpack 2.4.2 for a Typescript-based AngularJS 1.6 application. Whenever I make modifications to files like .ts, .js, and .less, webpack automatically scans for lint errors and notifies me about them. Although I'm unsu ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

Using Snap SVG in a React application with Next.js and TypeScript

Query I have been attempting to incorporate SnapSVG into my React project, but I am encountering difficulties getting it to function properly from the outset. Can someone provide assistance with the correct configurations? I do not have much experience wi ...

ES7 Map JSON introduces a new feature by using square brackets

Currently, I am utilizing core-js for the Map collection because it appears that ES7 Map includes a Map to JSON feature that is absent in ES6 Map. (ES6): JSON.stringify(new Map().set('myKey1', 'val123').set('myKey2', 'va ...

TS2532 Error: Potential uncertainty of an object being 'undefined' even after verifying its definition

Below is the implementation of a helper class that generates a hash: export default class PageUtil { private size: number; private step: PageUtilStep; private cursor: unknown[] | undefined; public constructor(size: number, step: PageUtilSt ...

Navigating through JSON object fields within Angular component [Version 11]

Check out this Angular service method that calls a basic REST API: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Token } from './Token'; import { map } fro ...

Traversing fields of a document within a Firestore collection using Angular

Attempts to retrieve the user's photoUrl based on their ID have been unsuccessful. Here is a snapshot of my firestore collection, can someone please guide me on how to access the photoUrl? https://i.stack.imgur.com/p2Zvm.jpg The main collection is &ap ...

Nuxt Error: The Vuex state should not be modified outside of mutation handlers when making changes through a plugin

Utilizing Firebase within my Nuxt project, I have a plugin where I invoke onAuthStateChanged to verify if the user is logged in. If so, I update the user state and redirect them to the dashboard using the code snippet below: import firebase from 'fir ...

Show targeted information from the array using the respective identifier

Is it feasible to exhibit data from a Vuex store array in a unique manner, comparable to the illustration provided below: <template> <div> <h1>{{this.$store.state.data.title}}</h1> <p>{{this.$store.state.da ...

Is npx create-react-app suggesting to remove a non-existent create-react-app package globally?

I'm encountering issues with npx create-react-app that involve global installations. I'm puzzled because I don't believe the create-react-app package is installed on my system. Here are some details: I initiate a new React project (using t ...

Converting an Observable containing an Array of StaffInterface objects to a plain Array of StaffInterface objects in @ngrx/store select

Trying to retrieve an Array<StaffInterface> from an Observable<Array<StaffInterface>> in ngrx store.select. The store.select method returns the Observable<Array<StaffInterface>>, which I then need to convert into an Array<S ...

The promise briefly returns a placeholder object before resolving with the actual response

Currently, I am working on a simple check to determine whether myAnswer contains an answer. The checking functionality is operating smoothly; however, the issue arises in the final function that aims to return the string obtained from myAnswer. Instead of ...

Exploring the Power of Typescript and Graphql Fragments

Utilizing codegen, I automatically generate TypeScript types and employ Apollo client to submit requests to the server. However, when I execute code generation for the given example, TypeScript fails to recognize that the people object contains firstName ...

What are the steps to initiate a new project using the CLI on a Linux operating system

I've got a project up and running in Vue JS with Node JS installed. Now I want to create a new project using CLI. Do I need to install another version of Node JS for this new project? ...

JavaScript's Blob to Base64 conversion using FileReader is failing to produce any output

In my typescript application, I am utilizing the FileReader to convert a blob into a base64 image for display within the template. adaptResultToBase64(res: Blob): string { let imageToDisplay : string | ArrayBuffer | null = ''; const re ...

The Vue.createApp function seems to be malfunctioning, whereas using the new Vue() method is functioning correctly

When running my code, I encountered the following error message: tesyya.js:16 Uncaught TypeError: Vue.createApp is not a function. My code snippet looks like this: const app = Vue.createApp({ data() { return { count: 4 } } }) const vm ...

Using the entire row as a toggle mechanism to select items in an office-ui-fabric detailslist, instead of relying on a small checkbox for selection

Currently, I am utilizing Office UI Fabric React components and I am aiming to enhance the default selection behavior for a DetailsList. At present, there is a difference in functionality between clicking on a row and clicking on the small checkbox located ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

What are some tips for creating scenes in Decentraland for newcomers?

What strategies can I employ, and what expertise/documentation/tools are necessary to construct scenes for Decentraland and deploy them on my property? I've been experimenting with the DCL Builder since it seems like the only thing I can actually do. ...