Vue 3 TypeScript Error 2339: The attribute xxx is not present in the type {

My tech stack includes Vue3 with TypeScript, axios, and sequelize. Currently, I am working on a form that contains just one textarea for users to post on a wall. Below is the script I have written in my form component:

<template>
  <div id="PostText" class="col-12">
    <form id="postTextForm">
      <div id="PostwriteContent">
        <label for="PostContent">
          <h2>Share your thoughts with us...</h2>
        </label>
        <textarea
          name="PostContent"
          id="PostContent"
          cols="65"
          rows="6"
          v-model="theNewPost.content"
          autocapitalize="sentence"
          form="postTextForm"
          maxlength="650"
          placeholder="Enter your text here..."
          required
          autofocus
        ></textarea>
        <button class="col-9" type="button" :disabled="!isFormValid" @click="sendMyPost">Post</button>
      </div>
    </form>
  </div>
</template>

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

export default {
  data() {
    return {
    errorMessage: String,
      theNewPost: {
        content: String,
        userId: Number 
      }
    };
  },
  methods: {
    sendMyPost(e:any){
      e.preventDefault();
      
      console.log("testPost >>" + this.theNewPost.content);
      console.log("theNewPost >>" + this.theNewPost);

      axios.post("http://localhost:3001/api/feed", this.theNewPost)
        .then((res) =>{ 
          console.log('Post online ;)' + res)
        })
        .catch((err) => {
          this.errorMessage = err.message;
          console.error("There was an error!", err);
        })

    }
  },
  computed:{
    isFormValid(){
      if (
        this.theNewPost.content !== ""
      ) {
        return true;
      } else {
        return false;
      }
    }
  },

};

</script>

However, I am encountering errors when using "this.". It seems that the names theNewPost and errorMessage cannot be found, even though I have defined them in data and used them in V-model.

Additionally, the two functions I have bound in my form are not running. Can you please help me identify the mistakes I have made? Thank you for your assistance ;)

Answer №1

If you want to add TypeScript support, you need to wrap the component using defineComponent():

import { defineComponent } from 'vue'

export default defineComponent({
  data() { ... },
  methods: { ... },
  computed: { ... },
})

Remember that the data() return values should be literals (without being initialized to String or Number):

data() {
  return {
    errorMessage: '',
    theNewPost: {
      content: '',
      userId: 0
    }
  };
}

Answer №2

I encountered the identical problem. Even though all the files were functioning properly, there seemed to be an issue with THIS particular file that was causing an error...

I utilized "ionic serve" to deploy locally and decided to remove 'lang=ts' from the script tag before adding it back in.

After recompiling everything, the error was no longer present :(

Perhaps there is a problem with caching... I have faced similar issues in the past...

Answer №3

If you are utilizing the Composition API, ensure that you have added setup in the script tag.

Illustration

Transforming this:

<template>
<div v-for="i in foo">{{i}}</div>
            ^^^^^^^^TS 2339
<template>

<script lang="ts">
const foo=[1,2,3]
</script>

Into this:

<template>
<div v-for="i in foo">{{i}}</div>
            ^^^^^^^^TS 2339
<template>

<script lang="ts" setup>
                  ^^^^^<-put here
const foo=[1,2,3]
</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

State in Vuex can be modified by invoking the store actions

Currently, I have implemented two functions in my store. One function retrieves data by making API calls, while the other function toggles changes on the "approved" cell. Everything seems to be functioning correctly, except for the fact that after toggling ...

What is the best way to export a default object containing imported types in TypeScript?

I am currently working on creating ambient type definitions for a JavaScript utility package (similar to Lodash). I want users to be able to import modules in the following ways: // For TypeScript or Babel import myutils from 'myutils' // myuti ...

After I subscribe, why do the variables of my object become undefined?

Just starting out with Angular and using Angular9. I attempted to subscribe to an observable in the following code: I have a service that makes an HTTP request and returns an Observable. The subscription appears to be working fine. ngOnInit() { this.in ...

What is the best way to declare strings within a Typescript interface?

I have an array of Projects with multiple strings in the stack property const projects: IProject[] = [ {name: '', description: '', stack: {'php', 'sql'}} ] What is the best approach for defining the interface? ...

Looking to pass a Vue data value or id from a hyperlink in order to load a new component and display the corresponding value or id?

Looking to implement a feature where clicking on a Vue component will load another Vue component with a specific ID or value from a form. Check out the code snippet below: <template> <div class="container"> <table cl ...

Is it possible to incorporate HTML content into the metadata within the head section of a Nuxt application?

Received HTML content from the backend that needs to be incorporated into the meta tag of the HTML head using nuxt. Encountered an error when attempting to display the received content View Error Outlined below is the code implementation: Snippet of Code ...

Tips on troubleshooting the issue when attempting to use a hook in your code

I am trying to implement a hook to manage the states and event functions of my menus. However, when I try to import the click function in this component, I encounter the following error: "No overload matches this call. The first of two overloads, '(p ...

Creating TypeScript interfaces from Laravel backend

I'm currently exploring ways to automatically generate TypeScript code from the API of my Laravel application. I have been using scribe for generating API documentation and then utilizing it to create TypeScript definitions. However, I am facing an is ...

Hydration has finished, but there are some discrepancies - Utilizing Ascii art within a vue component

I encountered an issue with displaying ascii art in the {{ name }} section of my component. While developing, a Vue warning popped up: Hydration text content mismatch in <pre> Followed by an error message: Hydration completed but contains mismatch ...

Executing several conditional calls in RxJS

I am currently facing an issue with conditional calls in RxJS. The situation involves multiple HTTP calls within a forkJoin. However, there are dependencies present - for example, the second call should only be made if a boolean value from the first call i ...

In TypeScript, if all the keys in an interface are optional, then not reporting an error when an unexpected field is provided

Why doesn't TypeScript report an error when an unexpected field is provided in an interface where all keys are optional? Here is the code snippet: // This is an interface which all the key is optional interface AxiosRequestConfig { url?: string; m ...

What is the best way to delay the rendering of my Vue component until a function call is finished?

After extensive research online, I have been unable to discover a specific solution to my issue. The problem is that I have a Vue component that relies on an init call and I need it to avoid rendering until the call is successfully completed. Once the ca ...

Can anyone help with displaying a PNG image in Vue/Node/Express? I am struggling to show the image that I sent from a Node.js server to a Vue app client

In my Node/Express application, I've set up a route like this: app.get('/get-image', function(req, res) { ... res.sendFile(path.join(__dirname, '..', account.profileImg)); }) Now in my client-side Vue app, I'm tryi ...

When the @change event is triggered, Vue data objects do not exhibit reactivity

Trying to figure out why the msg and show data parameters are not updating when triggered by @change. To ensure that these parameters are only updated upon successful file upload, I placed them inside the lambda function of onload: reader.onload = functio ...

File declaration for modules within modules

I'm currently working on a project that includes a Node JS module located at foo/bar.js. As I'm developing a TypeScript module in src/mymod.ts that needs to import foo/bar.js, I'm facing a challenge in creating a declarations file for the fo ...

general structure used to activate every page in vue 3

AppTopbar.vue <Dropdown v-model="selected" :options="storesLists" @change="onChange" optionLabel="name" :filter="true" /> onChange(event) { console.log(event.value.value); localSt ...

I'm baffled by how the community response is implemented in this particular TypeScript exercise on Exercism

I am currently learning TypeScript from scratch by working on exercises available on exercism Successfully completed the 5th exercise on Pangram. Below is my solution: class Pangram { alphabet = "abcdefghijklmnopqrstuvwxyz" constructor(privat ...

Uploading Files with Angular 2 using AJAX and Multipart Requests

I am currently working with Angular 2 and Spring MVC. At the moment, I have an Upload component that sends an AJAX request to the Spring backend and receives a response containing parsed data from a .csv file. export class UploadComponent { uploadFile: f ...

Guide to setting up value observation in React Context for optimal functionality

Imagine a scenario where there is a Parent Component that provides a Context containing a Store Object. This Store holds a value and a function to update this value. class Store { // value // function updateValue() {} } const Parent = () => { const ...

Tips for converting an external SVG file into a Vue3 component

I am currently working on a Vue3 project with Vite, Typescript, and script setup for my components. My objective is to retrieve an svg image from an S3 bucket (an external URL) and utilize it as an inline svg within my component, allowing me to set props s ...