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

How to Perform a Redirect to a Named Route in Vue.js?

Currently, I am in the process of working on a Vue.js project and have set up a route with the following configuration: { path: '/Cart', component: Cart, props: (route) => ({ payment_id: route.query.payment_id, payment_request_id: ...

Creating a service instance within the constructor in Angular 2

I'm new to Angular 2 and Typescript and I'm trying to wrap my head around DI. One thing that has been tripping me up is the way variables referring to a service are typed into the constructor in all the code examples I've come across. Why is ...

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

Exploring the synergies between Typescript unions and primitive data types in

Given the scenario presented interface fooInterface { bar: any; } function(value: fooInterface | string) { value.bar } An issue arises with the message: Property 'bar' does not exist on type '(fooInterface | string)' I seem ...

Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids. Here's a snippet from the Angular component code: this.orderService.getSpecyficOrders(ids) .subscribe(orders => { ... Where ids is an array of [{_id : ID }, ...

Enhancing Website Performance with Vue.js 2.0 Lazy Loading

I'm attempting to implement Lazy Loading for my components in Vue.js 2.0 (within a Laravel 5.3 project). As per the guidelines, I should proceed like this: Vue.use(VueRouter); const Forum = resolve => require(['./Components/Forum/Forum.vue& ...

Guide on verifying the presence of a value in a textbox using vue

I'm currently working on a form that requires only numbers and text input. Any characters like ., ,, or spaces are not allowed in the textbox. Here are some of the attempts I've made, but unfortunately, they did not yield the desired results: i ...

What is the best way to convert Arabic language HTML into a PDF document on the client side?

Utilizing jsPDF and vue js, I successfully implemented a feature to export PDFs. However, I encountered an issue with Arabic characters not displaying properly. Can anyone provide assistance in resolving this problem? ...

When is the best time to utilize v-layout within Vuetify 3?

I'm confused about the purpose and usage of the v-layout component in Vuetify 3. When looking at the documentation for the app-bar component, I noticed an example utilizing v-layout (GitHub code), but its impact is unclear: by removing the v-layout t ...

Connecting Angular modules via npm link is a great way to share common

Creating a project with a shared module that contains generic elements and components, such as a header, is my goal. This shared module will eventually be added as a dependency in package.json and installed through Nexus. However, during the development ph ...

Converting a TypeScript nested dictionary into a list of strings

I am currently working with a nested dictionary and my goal is to convert it into a list of strings. For example, the initial input looks like this: var group = { '5': { '1': { '1': [1, 2, 3], ...

NodeJS on Cloudlinux requires that the node modules for applications be stored in a distinct folder (virtual environment) designated by a symbolic link known as "node_modules"

I recently encountered an issue while trying to deploy my Nodejs/TypeScript web application on my cpanel shared hosting. The error I received stated: * Cloudlinux NodeJS Selector requires the node modules for the application to be stored in a separate f ...

Angular - Dropdown menu fails to display options

I encountered an issue with the JSON response from my Angular-12 API endpoint: { "message": "vehicle Model Detail.", "error": false, "code": 200, "results": { "vehiclemakes": [{ ...

How can I update a dropdown menu depending on the selection made in another dropdown using Angular

I am trying to dynamically change the options in one dropdown based on the selection made in another dropdown. ts.file Countries: Array<any> = [ { name: '1st of the month', states: [ {name: '16th of the month&apos ...

Failure to fetch data through Axios Post method with a Parameter Object

I've encountered an issue with Axios while attempting to make a post request with a parameters object to a Laravel route. If I use query parameters like ?username=user, the post request works successfully. However, when I use an object, it fails: Be ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

Error message: 'Vue is not defined' when using RequireJS

I'm facing an issue where the Vue object appears to be undefined in the browser after loading Vue with RequireJS. I'm puzzled by this situation and would appreciate any guidance that could help me narrow down the problem. It's worth mention ...

What sets apart the commands "vue create NewProjectsName" and "vue init webpack NewProjectsName"?

Can you explain the contrast between running vue create NewProjectsName and vue init webpack NewProjectsName commands within the Vue CLI? ...

Enhancing AG-Grid with live data updates post drag and drop interaction

Exploring AG-Grid for the first time within my Vue application has been challenging. I am currently facing an issue where the data does not update after a drag&drop event. To illustrate this problem, I have created a small example on Plunker import Vue ...

The type Observable<any> cannot be assigned to Observable<any> type

I am currently working with angular 5 and ionic 3. I have defined an interface: export interface IAny { getDataSource: Observable<any>; } Components that implement this interface must have the following method: getDataSource () { return ...