Validating the observable subscribe input parameter

Why is there no error or warning displayed in the subscribe parameter when defining the wrong parameter type in tsconfig?

For example, in the correct code below, if 'user' is of type 'UserDto', VS Code will identify it correctly. However, if a different type like 'AddressDto' is used, neither VS Code nor Typescript will flag it as an error.

This is due to common properties among all Dtos. For instance, if all Dtos have an ID property, the error check becomes ineffective. Is there a way to receive a hint that the exact type for the user variable is not being used?

Is there a tsconfig option or solution for this issue?

export interface UserDto { 
    id?: string;
    givenName?: string | null;
    surname?: string | null;
}

public onAcceptInvitation(): void {
    this.usersService.getSelf()
      .subscribe((user: UserDto): void => {
        Object.entries(user)
      });
  }

The 'AddressDto' has the property 'id'. Therefore 'AddressDto' and 'UserDto' have at least one property in common and TS will accept this.

export interface AddressDto {
    id?: string;
    street?: string | null;
    houseNumber?: string | null;
}

public onAcceptInvitation(): void {
    this.usersService.getSelf()
      .subscribe((user: AddressDto): void => {
        Object.entries(user)
      });
  }

The Api Endpoint looks like this:

public getSelf(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json'}): Observable<UserDto> {
        return this.httpClient.get<UserDto>(`${this.configuration.basePath}/api/Users/self`,
            {
                responseType: <any>responseType,
                withCredentials: this.configuration.withCredentials,
                headers: headers,
                observe: observe,
                reportProgress: reportProgress
            }
        );
    }

Solution: The issue lies in the Interface definition. When properties are nullable, Typescript may accept the new type without displaying errors.

Answer №1

I'm not entirely sure of the goal you are aiming for here, but I hope to offer some assistance.

Neither VS Code nor Typescript will flag it as the incorrect type

This is because in .subscribe((user: AddressDto)), you have already converted user into AddressDto, so naturally there won't be any errors.

If the API changes, I want my frontend to detect a build failure

In that case, the modification needs to be made in the getSelf() method so that it only returns a specific value.

For instance:

public getSelf(): Observable<AddressDto> {
    return this.http.get<AddressDto>(`${API_URL}/getself`);
}

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

Anticipate an asynchronous function causing an error in a Jest test scenario

If I were to play around and execute the code snippet below: await expect(async () => { const asyncFunc = async () => { return Promise.reject(new Error('Foo')) }; await asyncFunc(); }).toThrow(); I assumed ...

The "VsTsc" operation was unable to start due to issues with its provided input parameters

Encountering the following error when building an Asp.NetCore project in Visual Studio Enterprise 2017 Version 15.6.0. The error sometimes disappears upon restarting Visual Studio, but a permanent solution has not been found. Error MSB4064: The "Compu ...

how to adjust the width of a window in React components

When attempting to adjust a number based on the window width in React, I encountered an issue where the width is only being set according to the first IF statement. Could there be something wrong with my code? Take a look below: const hasWindow = typeof ...

When intercepted, the HttpRequest is being canceled

Solution Needed for Request Cancellation Issue Encountering a problem with the usage of HttpInterceptor to include the Authorize header in all HTTP requests sent to AWS API Gateway. The issue arises as all these requests are getting cancelled when interce ...

Guide to making a ng-bootstrap modal that retains a component's state

I am currently working on implementing a modal with Angular by following a tutorial on the ng-bootstrap website ( - in the "Components as content" section). However, I am facing a challenge where I want the component displayed in the modal to retain its st ...

The utilization of functions from a implemented interface results in the generation of a 'non-function' error

I recently created an interface that includes variables and a function. However, I encountered an issue when trying to utilize the implemented function for a specific class as it resulted in an 'ERROR TypeError: ...getPrice is not a function" Below ...

Implementing strict typing in Twitter widget to eliminate issues with accessing members

I'm struggling to properly type my Twitter widget in TypeScript. Currently, I am encountering several errors such as: ESLint: Unsafe call of an any typed value.(@typescript-eslint/no-unsafe-call) ESLint: Unsafe member access .catch on an any value.(@ ...

Is there a way to transfer innerHTML to an onClick function in Typescript?

My goal is to pass the content of the Square element as innerHTML to the onClick function. I've attempted passing just i, but it always ends up being 100. Is there a way to only pass i when it matches the value going into the Square, or can the innerH ...

Guide to releasing your Angular 6 library to npmjs along with a detailed README.md

I'm currently in the process of developing an Angular 6 library that I intend to share on npmjs. The library, named ng-as-multiselect-dropdown, is versioned on GitHub through the workspace project 'sample'. I used the Angular-CLI command &ap ...

Angular 4 enum string mapping reversed

Here is an example of a string enum: export enum TokenLength { SIX = '6', EIGHT = '8', } I am trying to retrieve the string value 'SIX' or 'EIGHT' by reverse mapping this enum. I have attempted various methods: ...

Material-UI: Error thrown when attempting to pass props to makeStyles in React due to missing property 'X' on type '{}'

Currently experimenting with Adapting based on props, you can find more information here import React from 'react'; import { makeStyles } from '@material-ui/core'; const useStyles = makeStyles({ // style rule foo: props => ( ...

To enable the "Select All" functionality in ag-grid's infinite scrolling feature in Angular 4, utilize the header check box

Is there a way to add a checkbox in the header of ag-grid for selecting all options when using an infinite row model? It seems that the headerCheckboxSelection=true feature is not supported in this model. Are there any alternative methods to include a che ...

Using an external variable within an internal function in TypeScript

I am facing a situation where I have a variable outside of a function that needs to be updated, but I am unable to access it using "this" as it is not reachable at that point in the code. export class GamesDetailPage { details : any = {}; type : St ...

Issue with Angular2 Property Change Notification

I have a directive called app.service.ts that holds the state data of the app. I'm using this directive in other components to access and modify the app state, which is functioning correctly. However, I encounter an error when I attempt to bind a pro ...

Is Angular 11 Compatible with Internet Explorer 5?

Is there a way to make Angular 11 compatible with Internet Explorer 5? I am developing an angular solution for a client whose default browser is Internet Explorer running on version 5 (by default). Initially, I am not supposed to change any browser configu ...

In TypeScript, Firestore withConverter may return a QueryDocumentSnapshot instead of the expected Class object

I'm currently exploring the usage of Firestore's withConverted method in Typescript to retrieve queries as instances of my customized class. Custom EventConverter Class import Event from "@/models/Event"; class EventConverter implemen ...

What is the significance of TypeScript's dual generic typing feature?

defineListenerShape< EventName extends string, EventData extends { [key in EventName]: unknown; } > = <E extends EventName>(data: EventData[E]) => void; enum EventName { Click = 'click', Hover = 'hover' ...

Retrieving the true value of semicolon as well as array elements from a URL in Angular

ngOnInit() { const id$ = this.route.paramMap.pipe(map((params) => params.get('id') || 0), map(n => Number(n))); id$.subscribe(id => { this.activeId = id; console.log("ActiveId",this.activeId); ...

Optional parameters in typed languages can either have zero or all parameters provided

I am delving into the world of typed functional programming and have embarked on implementing partial application with a focus on type safety. Issue at hand: I'm aiming to create a function that can take a function along with zero or all of its param ...

The Angular application encountered errors while trying to resolve main.ts, polyfile.test, and style.css

I encountered an issue while trying to run my Angular app in a Docker container. Here are the steps I followed: 1) Installed npm (v.3.5.2), node (v. 12.15.0), and angular CLI (v. 9.0.1) on my local machine 2) Created an Angular project locally using the ...