Why does TypeScript throw an error when accessing errorCode on t.error in Angular?

Discussão em 'Angular' iniciado por Jon, Fevereiro 14, 2025.

  1. Jon

    Jon Guest

    I'm using Angular with @ngneat/query and RxJS to handle API requests. In my code, I throw an object containing an errorCode, but TypeScript complains that errorCode does not exist on t.error.

    I have the following HTML:

    <div *ngIf="todos | async as todos">
    <div *ngIf="todos.error">error code: {{ todos.error.errorCode }}</div>
    </div>


    And in my TypeScript code:

    this.todos.subscribe((t) => {
    const errorCode = t.error?.errorCode; // TypeScript error here
    });


    Error:

    NG9: Property 'errorCode' does not exist on type 'Error'.

    Code Example


    Here’s the full reproducible example:
    StackBlitz

    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import { of, tap } from 'rxjs';
    import { injectQuery } from '@ngneat/query';
    import { CommonModule } from '@angular/common';

    @Component({
    selector: 'app-root',
    imports: [CommonModule],
    template: `
    <div *ngIf="todos | async as todos">
    <div *ngIf="todos.error">error code: {{ todos.error.errorCode }}</div>
    </div>
    `,
    })
    export class App {
    #query = injectQuery();

    todos = this.#query({
    queryKey: ['todos'],
    queryFn: () =>
    of({ data: { status: 500 } }).pipe(
    tap((response) => {
    if (response.data.status === 500) {
    throw { errorCode: response.data.status };
    }
    })
    ),
    }).result$;

    ngOnInit() {
    this.todos.subscribe((t) => {
    const errorCode = t.error?.errorCode; // TypeScript error here
    });
    }
    }

    bootstrapApplication(App);

    What I've Tried

    • I verified that the error is indeed an object ({ errorCode: number }) when thrown.
    • TypeScript seems to assume t.error is of type Error, which doesn't have errorCode.

    Why is TypeScript treating t.error as Error, and how can I correctly type it so that errorCode is recognized?

    Continue reading...

Compartilhe esta Página