Troubleshooting compilation issues when using RxJS with TypeScript

Having trouble resolving tsc errors in the code snippet below.

This code is using rxjs 5.0.3 with tsc 2.1.5

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/Rx';

let subject = new Subject();

Observable.merge(subject, Observable.interval(500))
  .startWith(new Date())
  .scan((acc, curr) => {
    const date = new Date(acc.getTime());
    date.setSeconds(date.getSeconds() + 1);
    return date;
  })
  .subscribe(v => {
    let today = v.toISOString();
    console.log(today);
  });

The errors encountered are:

node_modules/rxjs/Observable.d.ts(68,60): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/Observable.d.ts(68,70): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/observable/PromiseObservable.d.ts(40,31): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/observable/PromiseObservable.d.ts(41,26): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/operator/toPromise.d.ts(2,60): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/operator/toPromise.d.ts(3,79): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/operator/toPromise.d.ts(3,89): error TS2304: Cannot find name 'Promise'.
test.ts(10,31): error TS2339: Property 'getTime' does not exist on type 'number | {}'.
  Property 'getTime' does not exist on type 'number'.
test.ts(15,19): error TS2339: Property 'toISOString' does not exist on type 'number | {}'.
  Property 'toISOString' does not exist on type 'number'.

Answer №1

It seems like you're trying to call "Date" methods on a regular number here. It looks like "acc" is being treated as a date or has already been converted to a number and you are still trying to use it as a date.

If I were to make an educated guess, modifying this line:

const date = new Date(acc.getTime());

To something like this might help:

const date = new Date(acc).getTime();

This modification could potentially solve the issue you are facing. Alternatively, considering that you are returning "date":

const date = new Date(acc);
date.setSeconds(date.getSeconds() + 1);
return date.getTime();

Another approach you could take is:

let today = new Date(v).toISOString();
console.log(today);

Please refer to the documentation for "scan" (you may find using "seed" instead of "startWith" to be beneficial):

acc: Any - represents the accumulated value.
currentValue: Any - denotes the current value.
index: Number - signifies the present index.
source: Observable - indicates the current observable instance.
[seed] (Any): Refers to the initial accumulator value.

Answer №2

If you need to rectify the type errors, you can take the following steps.

npm install --save-dev @types/core-js

To address the remaining errors, I have assigned the types for acc and curr as any. The updated code below has been corrected and is now compiling and executing without any issues.

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/Rx';

let subject = new Subject();

Observable.merge(subject, Observable.interval(500))
  .startWith(new Date())
  .scan((acc: any, curr: any) => {
    const date = new Date(acc.getTime());
    date.setSeconds(date.getSeconds() + 1);
    return date;
  })
  .subscribe(v => {
    let today = v.toISOString();
    console.log(today);
  });

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

Encountering a "subscribe is not a function" error while attempting to utilize a JSON file in Angular 2

My attempt to import a JSON file into my service is resulting in the following error: Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…) The current state of my service file is as follows @Injectable() ...

What is the process for uploading an array of files with AngularFire2 and Firebase Storage?

I encountered a dilemma trying to find answers to my question. Most resources, like the AngularFire2 documentation and an informative tutorial from angularfirebase.com, only demonstrate uploading one file at a time. As I aim to construct a photo gallery CM ...

Deciphering the TypeScript type in question - tips and tricks

One of my abstract classes includes a static property with various properties, where default is consistently named while the others may have random names. public static data = { default: { //only this one always have 'dafault' name na ...

Struggling to make the paste event function in Typescript

Here is a snippet of my Typescript code: const pasteFn = (e: ClipboardEvent) => { const { clipboardData } = e; const text = clipboardData?.getData('text/plain'); console.log(text); }; window.addEventListener('paste', pas ...

Swap out the traditional for loop with a LINQ query utilizing the any method

In my TypeScript code, I have the following snippet: public executeTest(test: Test): void { const testFilters: Record<string> = getTestFilters(); let isTestingRequired: boolean = false; for (let i: number = 0; i < testFilters.leng ...

TypeScript failing to correctly deduce the interface from the property

Dealing with TypeScript, I constantly encounter the same "challenge" where I have a list of objects and each object has different properties based on its type. For instance: const widgets = [ {type: 'chart', chartType: 'line'}, {typ ...

When utilizing the Turf.nearPoint() function, it is important to consider the type of point being used. The documentation for Turf.nearestPoint() appears to be inaccurate

I have some code that needs to be transcribed from another system, so unfortunately I can't easily share it here. If I could, I would just post the entire project. Recently, I attempted to integrate into our project but encountered error messages. T ...

Unsure about the commit hash referenced in the tsd.json file

Explore the history of angular-ui-router d.ts file using the commit hash Within my tsd.json file, I have the following details: { "version": "v4", "repo": "borisyankov/DefinitelyTyped", "ref": "master", "path": "typings", "bundle": "typings/tsd ...

Using TypeScript to Implement Content Security Policy Nonce

I encountered an issue with my TypeScript Express project while attempting to implement a CSP Nonce using Helmet. app.use(helmet.contentSecurityPolicy({ useDefaults: true, directives: { scriptSrc: ["'self'", (req, res) = ...

TSLint warning: Duplicate identifier detected - 'err'

Currently facing an issue with tslint displaying the following error Shadowed name: 'err' Providing the code snippet for reference fs.readdir(fileUrl, (err, files) => { fs.readFile(path.join(fileUrl, files[0]), function (err, data) ...

Utilizing Typescript for constructor parameter assignments

Within my codebase, there exists an interface: export interface IFieldValue { name: string; value: string; } This interface is implemented by a class named Person: class Person implements IFieldValue{ name: string; value: string; const ...

When trying to click the button in Navbar.jsx, I encounter an error when attempting to invoke the setShowCart(true) function

I've encountered an issue while trying to call the setShowCart(true) function in Navbar.jsx. I'm unsure of how to fix this. import React from 'react' import Link from 'next/link'; import {AiOutlineShopping} from 'react-ic ...

Creating a ref with Typescript and styled-components: A comprehensive guide

Trying to include a ref into a React component looks like this: const Dashboard: React.FC = () => { const [headerHeight, setHeaderHeight] = useState(0); const headerRef = React.createRef<HTMLInputElement>(); useEffect(() => { // @ts ...

How to form an array using rxjs before the adding sequence is completed

I am currently exploring a way to utilize rxjs to achieve the following scenario: You have two observables, onAddObs and onRemoveObs. Assume that onAddObs.next() is triggered multiple times, adding "A", "B", "C". I aim to then extract ["A", "B", "C"]. .t ...

Developing Derived Classes in Typescript

I am looking to enhance my service class by creating a subclass where I can define functions with the same name but different implementations. My desired structure is as follows: httpWrapper.get //default is observables. returns observable httpWrapper.pr ...

Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I& ...

No matter the circumstances, the "Unexpected end of form" error consistently appears when attempting to upload files in Express

I'm facing a challenge in implementing a file upload API endpoint for my Express+no-stress+Typescript application. Initially, I attempted to use the express-fileupload library, but I quickly realized that it didn't integrate well with Typescript ...

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

Using TypeScript, implement a function that is called when a React checkbox's state changes to true

Currently, I am experimenting with the react feature called onChange. My goal is to update local data by adding a value when a checkbox is selected. Conversely, when the checkbox is unselected, I just want to display the original data. However, I find that ...

Saving a user with a BLOB avatar in Angular 5: Tips and Tricks for Success

As a newcomer to Angular, I am trying to figure out how to properly save a new user with an avatar. Can someone help me understand how to pass the Blob value of the avatar to my user Model for successful saving? Below is the code snippet I am working with ...