The unholy trinity of RxJS, Typescript, and the infamous 'Type Mismatch' error message

It's clear that I'm overlooking something obvious. The pseudo code below works perfectly in production, but my IDE (IntelliJ IDEA) is throwing an error that I can't solve. I can suppress it with

noinspection TypeScriptValidateTypes
, but I really want to understand what's causing it:

this.authService.onAuthStateChanged()
    .pipe(
        withLatestFrom(
            this.activatedRoute.queryParams.pipe(
                map(params => params['returnUrl'])
            )
        )
    )
    .subscribe(([authState, returnUrl]) => {
        // [...]
    });

The error message on the subscribe line states:

Argument type ([authState, returnUrl]: readonly [any, any]) => void is not assignable to parameter type Partial> | undefined

Additional relevant information?

// AuthState is just a plain old JavaScript object.
onAuthStateChanged(): BehaviorSubject<AuthState | undefined>

// This is Angular's params object.
// https://angular.io/api/router/Params
export declare type Params = {
    [key: string]: any;
};

I'm using RxJS ~7.5.0, and Typescript ~4.7.4. My Angular version is ^14.2.0, although this issue doesn't seem specific to Angular.

So, what should happen here? The onAuthStateChanged method emits either an AuthState object or undefined based on the user's login status. This is then combined with the query parameter called returnUrl, which is always a string.

Historically, the syntax used involved destructuring assignment signature ([authState, returnUrl]), and as mentioned, it works fine in practice. It also doesn't throw errors on StackBlitz. But I'm facing issues in IntelliJ...

Could this be related to a breaking change in the latest RxJS version?

withLatestFrom

  • Generic signatures have changed. Do not explicitly pass generics.

Source: https://rxjs.dev/6-to-7-change-summary#withlatestfrom

Even though it compiles and runs successfully. So, two questions:

  1. What is causing this error in IntelliJ?
  2. How can I resolve it? I've tried strongly typing all parameters without success...

Answer №1

To keep up with the latest developments, you can monitor the progress of the problem at WEB-57220

Eliminating the error may be possible by activating the Typescript language service under Preferences | Languages & Frameworks | TypeScript

Answer №2

Ensuring that onAuthStateChanged is defined either as a function returning a BehaviorSubject, or directly as a BehaviorSubject, will prevent any errors from occurring.

The code snippet provided below demonstrates the absence of any type errors:

type AuthState = {};

let onAuthStateChanged = new BehaviorSubject<AuthState | undefined>(null);
let onAuthStateChangedFunc: () => BehaviorSubject<AuthState | undefined>;

// This represents Angular's params object.
// Reference: https://angular.io/api/router/Params
type Params = {
  [key: string]: any;
};

class Foo {
  constructor(private activatedRoute: ActivatedRoute) {}

  foo() {
    onAuthStateChangedFunc() // or
    // onAuthStateChanged
      .pipe(
        withLatestFrom(
          this.activatedRoute.queryParams.pipe(
            map((params) => params['returnUrl'])
          )
        )
      )
      .subscribe(([authState, returnUrl]) => {
        // [...]
      });
  }
}

The variables [authState, returnUrl] are correctly identified as type AuthState and any respectively.

For further details, please visit this stackblitz link.

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

Error: Yarn is unable to locate the 'logform' module within the 'winston' build

Struggling to work with Yarn 2 in building a NodeJS application using the following script: "build": "rimraf ./dist && tsc" Encountering an error: .yarn/cache/winston-transport-npm-4.4.0-e1b3134c1e-16050844d2.zip/node_modules/w ...

Protractor test stalls when waiting for disabled element using async/await instead of control flow

We are currently designing end-to-end tests using async/await methodology for easier debugging. However, we have encountered an issue with a particular test that hangs on the line: await browser.wait(ExpectedConditions.presenceOf(appPage.getLogo())); I a ...

Encountering an issue while upgrading to Angular 10: Unable to interpret "tsconfig.json" as a valid JSON AST Object

I'm currently updating my Angular 9 app to Angular 10 and encountering this error: > Removing "Solution Style" TypeScript configuration file support. × Migration failed: Failed to parse "tsconfig.json" as JSON AST Object. PropertyNameExpected at l ...

Position the circles in a way that they align along the circumference of a larger

I need help arranging a group of circles around another circle without any of them overlapping. I have all the radius measurements for each circle, as well as the coordinates for the target circle. The target circle will always be large enough to contain ...

Tips for accessing a specific ListItem within the Menu Component using MUI for React

Within my code, I am working with a List that contains multiple ListItems pulled from an array called myCollection. Each ListItem has a MenuIcon element which triggers a menu to appear, providing the option to delete the specific item. Here is a simplified ...

Angular 6 - Assigning string value to a variable when a click event occurs

I want to store the text of a click event in a variable. Here is the current code I am using: <th (click)="sortedColumn = clickValue">Ask Price</th> When a user clicks on the table header, I need it to save the value "Ask Price" in t ...

TS2339: The function 'slice' is not found on the data type 'WritableSignal<Product[]>'

Currently, I am facing a challenge in my Angular 10.1.0 project while attempting to implement pagination by slicing my data array. The issue arises with the error message TS2339: Property 'slice' does not exist on type 'WritableSignal<Dat ...

How to combine and return an observable and a value simultaneously in an Angular service using RxJS

Within my Angular application, I am utilizing the ngx-bootstrap modal component. This modal is being used to provide observable callbacks when the modal is shown and hidden (onShown / onHidden) after a button click event. The code snippet for this functi ...

Ways to enhance this directive for displaying a unique error message using mat-error

When using AngularMaterial form components, I need to show an error message when the form control is in an invalid state. This message should be recalculated every time the status or value of the form control changes. I will provide the form control and er ...

Is it possible to create a QR Code using Ionic 5?

Is there a way to generate QR Codes in Ionic 5? I attempted it, but keep receiving an error stating that the qrcode element is not recognized. Here is my code: qrcode.html <ion-item> <ion-input type="text" placeholder="My QR d ...

What is the reason behind using `Partial<>` to enclose the Vue props?

I am currently working with a combination of technologies, and I am struggling to pinpoint the root cause of the issue. Here is the Tech Stack: Vue 3 TypeScript Vite VSCode / Volar unplugin-vue-macros (https://github.com/sxzz/vue-macros) unplugin-vue-com ...

Determining the Best Use of Types Versus Interfaces in TypeScript

It's puzzling to me when you might opt for a type over an interface for a variable in typescript. Let's consider the two options provided: type Player = { id: string; name: string; score: number; } interface Player { id: string; ...

How to create line breaks in Angular Material matTooltip elements?

I am currently utilizing Angular 7 along with Angular material matTooltip. My goal is to have the tooltip display each element on a separate line, similar to this: https://i.sstatic.net/faVoo.png However, I am encountering an issue where it displays thr ...

Make the if statement easier - Angular

Would you like to know a more efficient way to streamline this If statement? The variables are all strings and are reused in both conditions, but the outcome varies depending on whether it returns true or false. if(params.province && !params.str ...

Using routerLink within an ng-template causes RouterActiveLink to malfunction

A brand new application has been developed using "Angular 2" featuring three components: AppComponent Test1Component Test2Component The application consists of a single module (AppModule) that initializes and declares AppComponent, Test1Component, and T ...

Set up and run a SpringBoot + Angular web application on an external IIS server

When it comes to running a Spring Boot application locally, it's as simple as running it with the spring-boot:run command or executing the main class of the project. However, deploying the same application on an IIS Server can be a bit more challengin ...

The first click causes Highchart to display with varying heights

I have implemented a highchart within a chart object in HTML, with CSS defining the height and width of the chart object. Initially, upon first render, the chart has a height of 290px. However, when I click on the tab again, the chart stretches to a height ...

Difficulty in activating or deactivating form controls in Angular 2 upon receiving an HTTP response

When using formcontrol in Angular, I encountered an issue where I tried to disable the form control based on a variable assigned from an HTTP response. Angular2 gave me a warning message. The warning mentioned that it's not recommended to use the dis ...

What is preventing the availability of those array extensions during runtime?

Looking for a simple way to work with arrays, I decided to create this custom extension class: export class ArrayType<T extends IEntity> extends Array<T> { add(item: T) { this.push(item); } remove(item: T) { console.log(item); ...

Is there a way to open an image.png file in typescript using the "rb" mode?

Is there a way to open png files in typescript similar to the python method with open(path+im,"rb") as f:? I have a folder with png files and I need to read and convert them to base 64. Can anyone assist me with the equivalent method in typescript? This i ...