Working with Vue class-based components in TypeScript and setting props

Currently tackling a typescript-related issue within a class-based component and seeking guidance on a persistent error.

Below is the code snippet for my component:

<template>
  <b-message :type="statusToBuefyClass">
    <p>PLACEHOLDER</p>
  </b-message>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
@Component({
  components: {},
  props: {
    status: {
      type: String,
      required: false
    }
  }
})
export default class Foo extends Vue {

  // explicitly type status
  status!: string

  get statusToBuefyClass(): string {
    const statusHash: {
      init: string
      active: string
      inactive: string
      archived: string
    } = {
      init: 'is-warning',
      active: 'is-success',
      inactive: '',
      archived: 'is-danger'
    }

    return Object(statusHash)[this.status]
  }

  bar = this.status 

  mounted() {}
}
</script>

The code runs smoothly without any compilation errors. However, removing the explicit typing of status - status!: string - triggers the following error:

Property 'status' does not exist on type 'Foo'.

I have explored various resources but haven't found a solution that fits my scenario perfectly. In my tsconfig.json, I've set the following options as suggested in some discussions:

"strict": true,
"noImplicitThis": true,

Any insights or suggestions? Is there an alternative approach to avoid the redundancy of defining props and then typing them again within

export default class Foo extends Vue {...
?

Answer №1

It's a mystery to me how I overlooked this initially, but I have managed to find a solution that seems sustainable.

The key was utilizing the @Prop decorator. Here is the code snippet that now compiles without any errors:

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
@Component({
  components: {}

  // <--------------- props removed from here...

})
export default class Foo extends Vue {

  @Prop(String) status!: string // <--------- use @Prop decorator to define type and get prop from parent

  get statusToBuefyClass(): string {
    const statusHash: {
      init: string
      active: string
      inactive: string
      archived: string
    } = {
      init: 'is-warning',
      active: 'is-success',
      inactive: '',
      archived: 'is-danger'
    }

    // return statusHash
    return Object(statusHash)[this.status] // <------- no more compilation errors here
  }

  mounted() {}
}
</script>

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

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

The function "useLocation" can only be utilized within the scope of a <RouterProvider> in react-router. An Uncaught Error is thrown when trying to use useLocation() outside of a <Router>

When attempting to utilize the useLocation hook in my component, I encountered an error: import React, { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import { connect } from 'react-redux'; import { ...

Is it feasible to amalgamate the states of several child components into a single parent component state in NextJS/React?

Issue I am faced with the challenge of handling multiple Child components that can pass their state to a Parent component. Now, I am looking to render several Parent components within a Grandparent component and merge the states of each Parent into a sing ...

Automatically adjusting the placement of the hashtag within the URL when a button link is clicked in a Vue application

I am currently troubleshooting an issue with vue router within a custom library I am working on. The majority of the code was already developed before my involvement, and I have encountered a problem with implementing a back button on a specific page relat ...

Discovering the Solution: Angular 17's Answer to Troubleshooting Peer Dependency Conflicts

After upgrading Angular to version 17 using npm --force, my application was running smoothly in a local environment. However, when attempting to deploy it (via octopus deploy), the npm install process was automatically triggered by .Net, resulting in a lis ...

Maintaining database consistency for multiple clients making simultaneous requests in Postgres with Typeorm and Express

My backend app is being built using Express, Typescript, Typeorm, and Postgres. Let's consider a table named Restaurant with columns: restaurant_id order (Integer) quota (Integer) The aim is to set an upper limit on the number of orders a restaura ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

Build problems are occurring in the EC2 build box, but they do not arise when building locally

I encountered the following error in my EC2 build environment, but I am unable to reproduce it on my local machine: ERROR in node_modules/rxjs-compat/add/observable/dom/webSocket.d.ts(1,46): error TS2307: Cannot find module 'rxjs/websocket'. In ...

Is the hot module reload feature functioning correctly in Vue Native-Script?

I followed the instructions on step by step. After installing a testing app and attempting to modify the message on the Home component, I noticed that only the CSS reloads instantly without any issues. Strangely, my Android emulator does not respond to Ja ...

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

Efficient methods to transfer values or arrays between components in Angular 8 without relying on local storage

I am working on a project that involves two components: a login component and a home component. I need to pass user data from the login component to the home component without using local storage. Is there a way to achieve this in Angular 8? Below is the ...

Utilizing $store in field callback with VueJS and vue-form-generator

I've been utilizing the vue-form-generator component to work on my project. My goal is to update a variable in the store using the response from a callback function. Below is what I think is the relevant code (found inside the schema:fields property): ...

Is there a way to incorporate several select choices using specific HTML?

I am currently trying to dynamically populate a select tag with multiple option tags based on custom HTML content. While I understand how to insert dynamic content with ng-content, my challenge lies in separating the dynamic content and wrapping it in mat ...

Leveraging the Map function with Arrays in TypeScript

Is there a way to dynamically render JSON data into a component using array.map in Typescript? I am running into an error with the code snippet below. const PricingSection: FC<IProps> = ({ icon, title, price, user, observations, projects, intervie ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

What is the process for initiating a local Lambda edge viewer request?

Is there a way to run aws cloudfront lambda edge functions locally and simulate the event in order to observe the response from one of the four functions? I made modifications to the viewerRequest function of lambdaEdge, but I'm wondering if there is ...

Combining various API requests within a Vue component, which includes a for loop

I'm delving into the world of API chaining, specifically trying to link two different API calls within a 'notes' Vue component. My knowledge of promises is basic at best, but I'm eager to enhance my skills in this area. The initial API ...

How to retrieve an incorrect index from an array in Vue3?

Working on my task list project, I have an object within my main component structured like this: const tasks = ref([ { name: "Complete homework", completed: false }, { name: "Go for a run", completed: true }, I'm looping throu ...

Utilize a locally stored VueJs file rather than importing it from an external source

Starting my journey with VueJs using single file application has been quite interesting. Initially, I had everything in a single html page with both javascript and CSS styles embedded within it. To avoid fetching VueJs features online, I downloaded the V ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...