An issue arises in VueJS when employing brackets and the replace function in Typescript

My journey with the Typescript language has just begun, and I am excited to dive deeper into it. Currently, I am working on a SPA-Wordpress project as a hobby using Vite (VueJS). However, I am facing some challenges with the syntax when transitioning from dot notation to bracket.

<script lang="ts">
import axios from "axios";
import { ref } from "vue";

export default {
  data() {
    return {
      postsUrl: "https://localhost/wordpress/wp-json/wp/v2/news",
      queryOptions: {
        per_page: 6,
        page: 1,
        _embed: true,
      },
      pages: [],
      isLoading: false;        
    };
  },
  methods: {
    getPosts() {
      const isLoading = ref(true);
      axios
        .get(this.postsUrl, { params: this.queryOptions })
        .then((response) => {
          this.pages = response.data;
          console.log("Pages retrieved!");
          console.log(this.pages);
          isLoading.value = false;

        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  mounted() {
    this.getPosts();
  },
};
</script>

<template>
    <ul v-for="(page, index) in pages" :key="index">
      <h1>{{ page['title']['rendered'] }}</h1>    
      <p>{{ page.excerpt.rendered.replace(/(<([^>]+)>)/ig, "") }}</p>
  </template>

An issue arises with simple dot notation in Typescript:

Property 'excerpt' does not exist on type 'never'.ts(2339)

If brackets and parentheses are used, another error is triggered:

  <p>{{ page['excerpt']['rendered']['replace'](/(<([^>]+)>)/ig, "" ) }}</p>

This expression is not callable. Type 'never' has no call signatures.ts(2349)

Adopting a different structure resolves the Typescript error but results in an empty div:

  <p>{{ page['excerpt']['rendered']['replace(/(<([^>]+)>)/ig, "")']  }}</p>

The <h1> tag functions flawlessly with brackets, while dot notation triggers similar errors as with <p>.

  <h1>{{ page['title']['rendered'] }}</h1>

I would greatly appreciate some guidance on resolving this issue. Thank you for your assistance!

Attempts to enclose the replace function within square brackets and quotation marks have been unsuccessful.

Answer №1

It appears that the issue is not related to Typescript, but rather how I defined pages: [] within the <script> tag -- it requires a type declaration as well.

By using pages: [] as any[], or pages:[] as any, it functions correctly, displaying the desired excerpt without any html tags, and no errors are presented by Typescript.

Naturally, more specific declarations would be preferable to solely using any, although I have yet to determine the exact details for this refinement.

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

Setting an array of objects using TypeScript in the useState hook: A step-by-step guide

const response = { results: { items: [ { name: 'item1', }, { name: 'item2', }, { name: 'item3', }, { ...

Exploring the capabilities of Vue.js, including the use of Vue.set()

Just starting out with Vuejs and I have a query regarding the correct approach to achieve what I want. My Objective I aim to have some dates stored in an array and be able to update them upon an event trigger. Initially, I attempted using Vue.set, which ...

Issue: Using the command 'typings search' successfully locates a package, however, when attempting to install it using 'typings install', the process fails

I am currently attempting to install the Google Auth2 typings using 'typings': > typings search gapi.auth2 This command returns: NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED gapi.auth2 d ...

Parsing errors occurred when using the ngFor template: Parser identified an unexpected token at a specific column

In my Angular CLI-built application, I have a component with a model named globalModel. This model is populated with user inputs from the previous page and displayed to the user in an HTML table on the current page. Here's how it's done: <inp ...

Unable to import the Node.js array in the import() file

I have encountered an issue while building an array path for the Router.group function. The parameter passed to Router.group is added to the end of the this.groupPath array, but when I check the array data within an import(), it appears to be empty. What c ...

What sets apart exporting a component from importing its module in another module?

When working with Angular, consider having both module A and module B. If I intend to utilize "A-component" within components of module B, what is the distinction between importing module A in Module B compared to including the "A-component" in the exports ...

How can a functional component be created in VueJS using x-templates?

Looking to create a functional component in VueJS with a template as a single-file component? Utilizing x-templates means your component will be stored in a .html file. Want to transform the given component into a functional component? <!-- my_compone ...

The navigator.geolocation.watchPosition call did not return any available position information

I offer a service that monitors the position of devices: getLocation(opts): Observable<any> { return Observable.create(observer => { if (window.navigator && window.navigator.geolocation) { window.navigator.geolocat ...

What is the best method for saving information from a service to a class or interface in Angular 2?

I am currently in the process of developing a new web application and I am fairly inexperienced with Angular2. I am encountering an issue with one of my components that acts as a form for users to update their data. The problem lies in accessing specific ...

The functionality to verify the presence of a child element is not functioning correctly when using

Trying to determine the existence of a child, I have created a new Firebase list observable and also attempted with an object observable. Upon creating the observable, I verify if it exists or not; however, it always returns false. Database Structure: {R ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

Error location not displayed in Laravel/VueJS project console error message

Working on my laravel/Vuejs project, I encountered a challenging issue with VueJs troubleshooting. While developing a feature involving multiple vue components, everything seemed to be functioning as expected until I discovered an error message in the co ...

What is the best way to automatically close the Vue modal once the data has been successfully updated?

As a newcomer to vue.js, I created this code snippet for editing with a pencil icon <i class="mdi mdi-pencil" @click.prevent="$bvModal.show(type.title)" ...

Guide on creating a detailed list of categories mapped to specific classes that all adhere to a common generic standard

Most TypeScript factory patterns I've encountered rely on a named mapping between a name and the Class type. A basic implementation example: const myMap = { classOne: ExampleClass, classTwo: AnotherClass } (k: string) => { return new myMap[k] } ...

When trying to compile FirebaseUI with typescript and react-redux, users may encounter issues

I'm attempting to implement firebaseui for a login feature in react-redux using typescript. Here is the code snippet: import firebase from 'firebase'; import firebaseui from 'firebaseui'; import fire from '../FirebaseCreds&ap ...

Ionic - Smooth horizontal tab scrolling for sorted categories

Currently, we are developing a web/mobile application that includes horizontal scroll tabs to represent Categories. While this feature works well on mobile devices, it requires additional functionality for web browsers. Specifically, we need to add two arr ...

Updating component data in VueJS can sometimes be tricky, especially when dealing with the same

I have a route called '/posts' which includes a created() function that fetches data from an API using GET and displays the data on the page. Recently, I added a navbar to all pages with an input field for searching posts by tags. This tag-based ...

Issue: Unable to locate module - Unable to resolve 'core-js/modules/es.error.cause.js'

I've incorporated Vuexy Dashboard into my project, which utilizes Vue 2. Now, I'm in the process of upgrading it to Vue 3. However, I have encountered an error that has me stuck. Any assistance with this issue would be greatly appreciated. Thank ...

Unable to pass multiple objects as props in Vue component causing issues

Seeking help on passing multiple props to a component using v-for: <my-component v-for="(item, index) in items"></my-component> The data structure 'items' consists of: items: { 1: { name: "Apple", color: "Red" }, 2: { name: "Ba ...

The function "process" is not defined within the Vue.js framework

When attempting to utilize process.env.process.env.VUE_APP_SERVER_URL in my Vue project, I encountered the following error: Uncaught ReferenceError: process is not defined This project is built with webpack and executed using the npm start command. ...