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

What is the best way to create an Office Script autofill feature that automatically fills to the last row in Excel?

Having trouble setting up an Excel script to autofill a column only down to the final row of data, without extending further. Each table I use this script on has a different number of rows, so hardcoding the row range is not helpful. Is there a way to make ...

What is the best way to choose checkboxes from data that is passed dynamically?

https://i.stack.imgur.com/L3k59.png I am looking to add an edit feature to my application. When the user clicks on the edit option, they should be taken to a different page with the previously entered value displayed. While I have successfully retrieved ...

The Context API's `useContext` hook appears to be malfunctioning, persistently

My situation is as follows: export const LocationContext = createContext(null); export const LocationProvider = LocationContext.Provider; export const useLocationContext = () => useContext(LocationContext); Using the Provider: export const Search = () ...

What is causing the issue with TypeScript's React.createRef() and its compatibility with the material-ui Button element?

Running on React version 16.13.1, my component class includes a Material-UI Button component and a RefObject to access the button element. class Search extends React.Component<any, any>{ constructor(props: any) { super(props) this.streetV ...

Linking Redux to the highest level of my application is not functioning as expected

I have been attempting to troubleshoot this code for quite some time now, but I am struggling to identify the issue at hand. My main goal is to establish a connection between my top-level application and the redux store. However, every time I try, the stor ...

Using React with Typescript: Can the parent component access data fetched from a nested child component?

Can I access data retrieved from a child component (using a graphql query) in a parent component? For example, how can I use the data fetched by React-component-4 in React-component-1? Is there a way to do this or do I have to duplicate the data fetching ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...

Necessitating derived classes to implement methods without making them publicly accessible

I am currently working with the following interface: import * as Bluebird from "bluebird"; import { Article } from '../../Domain/Article/Article'; export interface ITextParsingService { parsedArticle : Article; getText(uri : string) : B ...

Encountering a type error with gatsby-plugin-dark-mode in a Typescript Gatsby setup

Issue with Layout warning in index.tsx when hovering: (alias) const Layout: ({ children }: Props) => JSX.Element import Layout Type '{ children: Element[]; }' is missing the following properties from type 'Props': theme, >toggle ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

The Material UI Datagrid is failing to display any data

I'm currently facing a challenge that has left me scratching my head. I've implemented Material UI Datagrids, but for some reason, I can't get it to populate with data, and the reason eludes me. Even though the Component profiler shows that ...

Cluster multiple data types separately using the Google Maps JavaScript API v3

I am looking to implement MarkerClusterer with multiple markers of various types and cluster them separately based on their type. Specifically, I want to cluster markers of type X only with other markers of type X, and markers of type Y with other markers ...

The absence of a template or render function in a Vue.js 3 and Quasar 2 component has resulted in an

I am currently working on creating a dynamic component and passing a prop to it. However, I am encountering a warning message that says: Component is missing template or render function. Although the component is being rendered, I am still receiving the wa ...

The DataGrid is only displaying a single result instead of multiple results

I'm having difficulty displaying all the results in this MUI data table. Currently, it is only showing one result instead of all, and I can't figure out what I'm doing wrong. If you have any suggestions or best practices on how to properly ...

utilize the getStaticProps function within the specified component

I recently started a project using Next.js and TypeScript. I have a main component that is called in the index.js page, where I use the getStaticProps function. However, when I log the prop object returned by getStaticProps in my main component, it shows a ...

Maintaining the order of the returned values type is crucial when working with mapped objects in Typescript

Currently, I am developing a basic mapper function for objects. This function is designed to take an array of object properties and then return an array containing the corresponding values of these properties. The function works as intended; however, I hav ...

Using Angular: A guide to setting individual values for select dropdowns with form controls

I am working on a project that involves organizing food items into categories. Each item has a corresponding table entry, with a field indicating which category it belongs to. The category is represented by a Guid but displayed in a user-friendly format. C ...

Issue with the physical back button on Android devices

Whenever I press the physical Android Button I encounter the following error: While executing, an unhandled exception java.lang.IndexOutOfBoundsException: setSpan (2..2) goes beyond length 0 Here is my app.routing.ts import { LoginComponent } from " ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...