Typescript error: The value "X" cannot be assigned to this type, as the properties of "Y" are not compatible

Disclaimer: I am relatively new to Angular2 and typescript, so please bear with me for any errors.

The Challenge: My current task involves subtracting a start date/time from an end date/time, using the result in a formula for my calculation displayed as "calc". The issue arises when attempting to use a mathematical operation within this formula which leads to various errors during transpilation:

1 mock-orders.ts(4,14): error TS2322: Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order[]'.

Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order'.

Types of property 'checks' are incompatible.

Type 'string' is not assignable to type 'number'.

Here is where the problem occurs in the child component. Please note line 28 where this.calc is defined:

// order.ts
import { Component, OnInit } from '@angular/core';

export class Order {
    order_no: string;
    scheduled: string;
    lateral: string;
    start_time: string;
    checks: number;
    stop_time: string;
    status: string;
    approx_cfs: string;
    approx_hrs: string;
    approx_af: string;
    calc: number;

    constructor(data: {} = {}) {
    this.order_no = data["order_no"] || "";
    this.scheduled = data["scheduled"] || "";
    this.lateral = data["lateral"] || "";
    this.start_time = data["start_time"] || "";
    this.checks = data["checks"] || "";
    this.stop_time = data["stop_time"] || "";
    this.status = data["status"] || "";
    this.approx_cfs = data["approx_cfs"] || "";
    this.approx_hrs = data["approx_hrs"] || "";
    this.approx_af = data["approx_af"] || "";
    this.calc = (!this.stop_time ? ((new Date().getTime() - new Date(this.start_time).getTime()) / 1000.0 / 60.0 / 60.0) * this.checks * 0.0825 : ((new Date(this.stop_time).getTime() - new Date(this.start_time).getTime()) /1000.0 / 60.0 / 60.0) * this.checks * 0.0825); 

    console.log(this.calc);
    };

};

I suspect that one of the issues lies in performing math operations on dates and then assigning the outcome to a number type.

Next, we have the call to this component for usage in the service:

// order.service.ts
import { Injectable } from '@angular/core';

import { Order } from './order';
import { ORDERS } from './mock-orders';

@Injectable()
export class OrderService {
  getOrders(): Promise<Order[]> {
    return Promise.resolve(ORDERS);
  }
}

The following file represents the data arrays pulled each time the service runs to illustrate what will be received from the database:

// mock-orders.ts
import { Order } from './order'

export const ORDERS: Order[] = [ 
    {order_no: '12345',
    scheduled: '08/16/16 13:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/16/16 15:45',
    checks: '23.25',
    stop_time: '08/17/16 15:30', 
    status: 'Delivered',
    approx_cfs: '25.00',
    approx_hrs: '22',
    approx_af: '45.38',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '', 
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    ...
];

Answer №1

When using Date.parse(), the input is first cast into a number and then converted into an equivalent date. In JavaScript, if the input contains characters other than numbers like '-' or '/', it will result in NaN, causing Date.parse to also return NaN. In such cases, you can use new Date(str: String) to create a date object from a valid date string. Additionally, the getTime() function can be utilized for performing mathematical operations on dates.

let data = {
  order_no: '12346',
  scheduled: '08/17/16 11:45',
  lateral: 'L1-8-1-T7, L1-8-1-T6',
  start_time: '08/17/16 15:30',
  checks: '20.25',
  stop_time: '', 
  status: 'Running',
  approx_cfs: '25.00',
  approx_hrs: '10',
  approx_af: '20.63',
 };
this.order_no = data["order_no"] || "";
this.scheduled = data["scheduled"] || "";
this.lateral = data["lateral"] || "";
this.start_time = data["start_time"] || "";
this.checks = data["checks"] || "";
this.stop_time = data["stop_time"] || "";
this.status = data["status"] || "";
this.approx_cfs = data["approx_cfs"] || "";
this.approx_hrs = data["approx_hrs"] || "";
this.approx_af = data["approx_af"] || "";
this.calc = (!this.stop_time ? ((new Date().getTime() - new Date(this.start_time).getTime()) / 1000.0 / 60.0 / 60.0) * this.checks * 0.0825 : ((new Date(this.stop_time).getTime() - new Date(this.start_time).getTime()) /1000.0 / 60.0 / 60.0) * this.checks * 0.0825); 

console.log(calc);

Answer №2

It seems that the problem lies in attempting to assign a string value to the checks variable, which is designed to store numbers.

start_time: string;
 checks: number;
 stop_time: string;

Currently assigned values are:-

start_time: '08/17/16 15:30',
 checks: '20.25',
 stop_time: '',

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

Showcasing Items Within JSON Object in Angular

I am dealing with a JSON database that contains nested Objects: { "characters2": [ { "campaign":"Menagerie Coast", "index": 1, "name": "Mark Whithershmitz", "portrait": "assets/pics/markW.jpg", "affiliation": "Kryn Dynast ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Node/Angular application facing a breach in content security

After working on a website built with node/express/angular/javascript, I returned to the project months later only to find that I couldn't display any page of the application when running it locally on node js. The error message "cannot get "{webpage} ...

What is the process of transforming two forms into components and then integrating those components into a view in Angular 5?

Currently, I have two forms running smoothly on the same component as shown in InfoAndQualificationComponent.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from "@angular/forms"; @Component({ selector: ...

Incorrect types being identified

What is the reason behind the callback assuming the type string | number | boolean instead of determining the exact type based on the property passed as the first argument in the carWithListener.on function? const car = { paint: "red", ...

The process of removing and appending a child element using WebDriverIO

I am trying to use browser.execute in WebDriverIO to remove a child element from a parent element and then append it back later. However, I keep receiving the error message "stale element reference: stale element not found". It is puzzling because keepin ...

Guide on making a Mapped Type in TypeScript using dynamic generic parameters

I am working with an object that contains one or more PreparedStatement. I am looking to create a general type definition for this object. Is there a way to achieve this in code? type PreparedRequest<Input, Result> = { input: Input; result: Resul ...

The issue of Rxjs Subject in Angular2 running twice persists even after unsubscribing

Currently, I am developing a desktop application using angular2 and electron with a download feature integrated within it. The code for my DownloadService looks like this: import {Injectable} from '@angular/core'; import {Subject} from "rxjs"; ...

Ways to link information from one entity to another

Currently, I am utilizing the TMDB API to showcase movies along with their respective genres. In my code, I have two objects where I retrieve details for movies and genres as shown below: listTrendingMovies() { this.listMediaService.listTrendingMovie ...

Similar to the "beforesend" functionality in JavaScript, there is a corresponding feature

When attempting to post a comment in my ionic app using the Wordpress api, I encountered error 401 (unauthorized) indicating that the Wordpress api does not recognize me as logged in. This is the code I am using: postComment(params?: any) { let nonce = l ...

What is the proper way to include type annotation in a destructured object literal when using the rest operator?

When working with objects, I utilize the spread/rest operator to destructure an object literal. Is there a way to add type annotation specifically to the rest part? I attempted to accomplish this task, but encountered an error when running tsc. const { ...

Tips for passing the same value to two components using vuejs $emit

Can someone help with typing in Main, where the value can also be Test World? You can view a sample here >>> Sample The issue I'm facing is that when a user adds an item to the cart, the cart shows one more than it should. I've tried t ...

SlidingPane header in React disappearing behind Nav bar

Here is the code snippet from my App.js file: export class App extends React.Component { render() { return ( <BrowserRouter> <NavigationBar /> <Routes /> </BrowserRout ...

Initiate monitoring for child component modifications

I'm looking to disable 'changeDetection' for the parent component while enabling it for the child component. Can you provide an example of how this can be achieved? The parent component contains static data, meaning change detection is not ...

How can data be transferred between controllers in Angular 2 without using URL parameters or the $state.go() function?

I've encountered an issue where I need to pass a parameter from one controller to another without it being visible in the URL. I attempted to do so with the following code: this.router.navigate(['/collections/'+this.name], {id: this.id}); ...

Creating a function that takes a second parameter inferred from a mapped type, depending on the first parameter given

Here is a snippet of code similar to the example provided: export enum Group { FOO = 'foo', BAR = 'bar', BIZ = 'biz' } interface Mapping extends Record<Group, any> { [Group.FOO]: {fooString: string; fooN ...

Angular is having trouble progressing after a stylesheet has been chosen

$ ng new my-app ? Do you want to include Angular routing in your project? Yes ? Which stylesheet format do you prefer to use? CSS Unfortunately, the next steps are not proceeding as expected. The process seems to be stuck and even keyboard shortcuts like ...

Every time you try to import a config.json file in Typescript, it never fails

I have the most recent version of Visual Studio Code installed. Visual Studio Code is currently utilizing TypeScript v3.3.3. I've successfully installed the following packages via npm, both locally (save-dev) and globally: TestCafe v1.1.0 Core-JS v ...

What is the method for defining the type of a variable without assigning a value to it?

Working on an Angular 11 project using Typescript with Strict Mode, I encountered the following issue: export class AvatarComponent { @Input() user: UserModel = null; } This resulted in a compilation error: Type 'null' is not assignable to ty ...

An issue in Angular 2 where the immediate parent component fails to receive and respond to events triggered by a child

In my basic angular setup, I have 3 components structured as follows: car-component acts as the main or parent component. carousel-component (child of car-component, *uses ng-content) child-component (child of carousel-component) The button inside the c ...