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

The GET API is functioning properly on Google Chrome but is experiencing issues on Internet Explorer 11

Upon launching my application, I encountered an issue with the v1/validsColumns endpoint call. It seems to be functioning properly in Chrome, but I am getting a 400 error in IE11. In IE v1/validCopyColumns?category=RFQ&columns=["ACTION_STATUS","ACTIO ...

Angular Service Worker: 504 error encountered during application deployment refresh

After building my Angular 8 project with ng build --prod, I serve it from the /dist folder using http-server. The app still works even after stopping it thanks to the service worker. The project successfully registers its service worker and I am able to ...

Creating a custom URL in a React TypeScript project using Class components

I have been researching stack overflow topics, but they all seem to use function components. I am curious about how to create a custom URL in TypeScript with Class Components, for example http://localhost:3000/user/:userUid. I attempted the following: The ...

Is there a way to restrict an array to only accept distinct string literals?

export interface IGUser { biography: string; id: string; ig_id: string; followers_count: number; follows_count: number; media_count: number; name: string; profile_picture_url: string; shopping_product_tag_eligibility: boolean; username: ...

Using Typescript to implement an onclick function in a React JS component

In my React JS application, I am using the following code: <button onClick={tes} type="button">click</button> This is the tes function that I'm utilizing: const tes = (id: string) => { console.log(id) } When hovering ov ...

Encountered a problem with regular expressions in Angular 2 - a Module parse error due to an octal literal in strict mode

Greetings, I have encountered an issue with a regular expression in my environment.ts file. export const environment = { passwordPolicy: "^(?!.*(.)\1\1)(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}.*$" }; Unfortunately, whe ...

What could be causing this peculiar behavior in my React/TypeScript/MUI Dialog?

My React/TypeScript/MUI application has a dialog that displays multiple buttons. Each time a button is clicked, the dialog function adds the button value to a state array and removes it from the dialog. Although it seems to be working, there is an issue wh ...

Islamic or Persian Date Packer for Oracle Application Express

Can anyone provide guidance on integrating a Hijri or Persian Date Picker in Oracle Apex? Looking for suggestions. Thanks! ...

What causes React Hook Form to return undefined upon submission?

I am currently working on a project using TypeScript. In this project, I have a form that should output 4 values after submitting the form. However, only the input field linked to the controller is sending a value, while the others are returning undefined: ...

"Exploring the world of Typescript with the Drawflow library

Currently, I am integrating the fantastic Drawflow library created by @Jerosoler (available at: https://github.com/jerosoler/Drawflow) into my PrimeNg project. User @BobBDE has provided typescript definitions for this library here: https://www.npmjs.com/p ...

"Implementing an abstract method in a class by overloading it with a generic type that

// Greetings from the TypeScript Playground, a platform where you can experiment with TypeScript code. type Constructor<T> = new (...args: any[]) => T; class ServiceChecklistResponse { } class AnotherModel { } abstract class AbstractView { ...

What causes the left click to not trigger in Kendo's Angular Charts?

My homepage features a simple bar chart that displays correctly, but I am having trouble capturing the left click event (the right click works fine). This is an example of code from my template: <kendo-chart *ngIf="(dataExists | async)" [ ...

Using SCSS based on the browser language in Angular: A Step-by-Step Guide

Is there a way to implement SCSS that is dependent on the user's browser language? When I checked, I found the browser language specified in <html lang = "de"> and in the CSS code as html[Attributes Style] {-webkit-locale: "en&quo ...

The type definition file for 'node' cannot be located

I've encountered some unusual errors after updating angular, webpack, and typescript. Any suggestions on what might be causing this? When I attempt to run the application with npm start, I'm seeing the following errors: [at-loader] Cannot find ...

Combining ngModel and ngClass in Angular: a comprehensive guide

I have implemented the following code in Angular 6 using Visual Studio Code <div [ngClass]="{'disabled': isReadOnly}"> <label class="switch"> <input type="checkbox" name="Gender" ...

Converting JSONSchema into TypeScript: Creating a structure with key-value pairs of strings

I am working with json-schema-to-typescript and looking to define an array of strings. Currently, my code looks like this: "type": "object", "description": "...", "additionalProperties": true, "items": { "type": "string" ...

What are some ways to leverage a promise-returning callback function?

Here is a function that I have: export const paramsFactory = (params: paramsType) => { return ... } In a different component, the same function also contains await getPageInfo({ page: 1 }) after the return .... To make this work, I need to pass a cal ...

transitioning from angular cli version 1.7 to version 12

Looking for a detailed guide on upgrading from version 1.7 to the latest Angular version (12/11)? I currently have an app running on version 1.7 and couldn't find a step-by-step process here: upgrading angular Would it be safe to assume that the upgr ...

Encountered an error while attempting to install the @typescript-eslint/eslint-plugin

After starting the installation process for eslint plugins, I encountered an issue with @typescript-eslint/eslint-plugin. The plugin requires installation using--legacy-peer-deps, but this approach may introduce potential bugs by accepting an incorrect an ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...