Using Typescript to return a specific data type

I am facing an issue with my dataSync service where TypeScript is referring to the returned data as type object instead of type <WebPost>, which is causing my code to break. In the dataSync service, I receive an error when hovering over the data parameter in the resolve(data) line.

Argument of type '{ _id: string; caption: string; comments: [string]; likes: [string]; price: number; image: string; forUser: string; likesLength: 1; commentsLength: 1; isLiked: boolean; }' is not assignable to parameter of type 'WebPost | PromiseLike<WebPost>'.

How can I resolve this issue?

Here is the method in my component:

getPostFromUrl() {
    this.route.params.subscribe(params => {
      const id = params['id'];
      this.dataSyncService.getPostData(id).then(data => {
        this.data._id = id;
        this.data.caption = data.caption;
        this.data.comments = data.comments;
        this.data.likes = data.likes;
        this.data.price = data.price;
        this.data.image = data.image;
        this.data.forUser = data.forUser;
        this.data.isLiked = data.isLiked;
        this.data.likesLength = data.likesLength;

        this.isData = true;
      });
    });
  }

Here is the dataSyncService:

getPostDataP(id): Promise<WebPost> {
    return new Promise<WebPost>((resolve, reject) => {
      this.authService.getPostP(id).subscribe(d => {
        if (d.success) {
          const data = {
            _id: '',
            caption: d.data.caption,
            comments: d.data.comments,
            likes: d.data.likes,
            price: d.data.price,
            image: d.data.imageUrl,
            forUser: d.data.forUser,
            likesLength: d.data.likes.length,
            commentsLength: d.data.comments.length,
            isLiked: d.data.isLiked
          };
          resolve(data);
        } else {
          reject();
        }
      });
    });
  }

Here is the definition of the WebPost type:

export interface WebPost {
  _id: string;
    image: string;
    forUser: string;
    price: number;
    likes: [string];
    comments: [object];
    caption: string;
    likesLength: number;
    commentsLength: number;
    likessLength: number;
    isLiked: boolean;
}

Answer №1

When defining your interface WebPost, make sure to utilize string[] and object[] instead of [string] and [object] in order to create arrays of strings / objects.

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

Common Errors in Angular 2 due to TSLint

I am encountering multiple errors in my code. I am using Angular 2 with TSLint: constructor(http: Http) { this.http = http; --> let currentUser = JSON.parse(localStorage.getItem("currentUser")); this.token = currentUser && currentUser.t ...

Is it possible to define react-router v6 routes within a functional component?

I have developed an application that requires users to log in before accessing it. I attempted to implement it using the following code: import React, {useState} from 'react'; import {Route, Routes} from 'react-router-dom'; import type ...

Retrieving source in Angular from an async function output within a specified time limit

I have a quick query :). I'm attempting to retrieve the image src from an async function, but so far, I haven't had much success. This is what I have: <img [src]="getProductImage(articleNumber)"/> and in my TypeScript file: publi ...

The valid and pristine properties of the Angular 2 form component are coming back as undefined

This is the code I have written: <form (ngSubmit)="onSubmit()"> <label>Cat Name</label> <input required #name="ngModel" [(ngModel)]="model.catName" name="catName" /> <br> <div [hidden]="catName.valid || catName.pristine" c ...

Error encountered when trying to use the .find function in Typescript: "The expression is not callable."

Environment Details: typescript 4.5.5 Error Summary An issue occurred stating: "This expression is not callable. Each member of the union type '{ <S extends User>(predicate: (this: void, value: User, index: number, obj: User[]) => value ...

What is the approach to merge an inner observable in RxJs with the outer observable and produce a single array as output

Whenever I execute the following code: timer(1000).pipe( expand(() => of('a')), take(3) ) .subscribe(data => alert(data)); I receive three alerts: one with 0, another with 'a', and a third one also with 'a'. I wo ...

Error occurring with the gulp task runner

Encountering an error while using the task runner for my "gulp" file. My project involves Angular 2 and Asp.net Core. The "typings" folder is set up with a "typings.json" file that contains the following: { "resolution": "main", "tree": { "src": ...

Node was experiencing difficulty locating a module alias that had been defined in the tsconfig file and package.json

I'm currently working on deploying a typescript project in production mode. You can find the code on Github here Executing npm run start:dev launches the server at http://localhost:3000/ Running npm run build generates the dist folder The definitio ...

Binding an ID to an <ion-textarea> in Ionic 3

Can an ID be assigned to an ion-textarea? For example: <ion-textarea placeholder="Enter your thoughts" id="thoughtsBox"></ion-textarea> Thank you very much ...

How can Material UI React handle long strings in menu text wrapping for both mobile and desktop devices?

Is there a way to ensure that long strings in an MUI Select component do not exceed the width and get cut off on mobile devices? How can I add a text-wrap or similar feature? Desktop: https://i.sstatic.net/lo8zM.png Mobile: https://i.sstatic.net/8xoW6. ...

Form: Initiate a manual valueChange

Currently, I am in the process of constructing a form using FormBuilder. My goal is to invoke another function whenever one of my FormControl elements is updated. To achieve this, I have opted to utilize valueChanges. However, I am facing an issue where I ...

Warning issued by Angular 7 indicating the usage of the routerLink directive and advising against navigation triggered outside the Angular zone

Encountering difficulties while working with the Angular framework to ensure smooth functioning of my application, I am currently facing an obstacle with routing. The structure includes a main AppComponent and a app-routing.module.ts file for navigation ma ...

The error message encountered while using webpack with TypeScript and React is: "Unexpected token React.Component

I am currently working on setting up a project using webpack, typescript, and react. I have implemented babel to transpile my typscript/react code. However, when starting the development server, I encountered the following error: Module parse failed: Un ...

What is the best way to show TypeScript code using "<code>" tags within an Angular application?

I am looking to showcase some TypeScript (angular code) as plain text on my website using prismjs. However, the Angular framework is executing the code instead. How can I prevent it from running? I have attempted enclosing it within pre and code tags wit ...

The ngFor directive in Angular should be used with the Filter pipe to ensure that

Having a Filter implemented in my Angular Project that fetches data from Firebase. The current status in the Filter is as follows: Name 1: Lea Muster Name 2: Bruno Mustermann Name 3: Lea Muster Name 4: Gabriela Musterfrau The goal is to show duplicate e ...

Roll out a custom-built server for an Angular 7, MongoDB, Express, and Node application

I am seeking to host my Angular application with Node.js, MongoDB, and Express.js on a server of my own. My current deployment method involves: -> ng build --prod (generates output in the dist folder) -> ng serve from the dist directory To start th ...

Tips for adjusting the width of the box on a BoxPlot chart in Apex charts

Currently, I am utilizing apexcharts(version 3.35.3) within an Angular project and I am looking to adjust the width of the box. After reviewing the documentation for apexcharts, I have not been able to find any specific option that allows me to modify the ...

After a duration of 4 minutes, an ERR_EMPTY_RESPONSE is thrown in response to the

My angular 5 node app involves sending a request to the server and waiting for a response. There are instances where the response takes around 5-6 minutes to arrive. However, an ERR_EMPTY_RESPONSE error is triggered by the http method after just 4 minutes ...

What sets property binding with methods in Angular apart from using @Output() and EventEmitter?

Consider a scenario where I have a set of parent-child components in Angular structured like this: Child component class: export class ChildComponent { @Input() addTask:any; } Child component template: <button (click)="addTask('cleaning&a ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...