Ensuring the validity of HTTPClient requests in Angular 4 through typechecking

Curious about the correct way to utilize the HTTP Client in Angular 4 with type checking? According to the official documentation at https://angular.io/guide/http, here is an example:

Imagine we have a Cake:

export interface Cake {
  numberOfCandles: number;
  diameter: number
}

and a CakeService:

@Injectable()
export class CakeService {

  public getCake(cakeUrl: string): Observable<Cake> {
    return this.http.get<Cake>(cakeUrl);
  }
}

Seems straightforward. I decided to run a test to observe its functionality:

it('should get one cake', inject([CakeService, HttpTestingController], (http: CakeService, httpMock: HttpTestingController) => {
http
  .getCake('testurl')
  .subscribe((data: Cake) => {
    expect(data.numberOfCandles).toBe('Test');
  });
const req = httpMock.expectOne('testurl');
expect(req.request.method).toEqual('GET');
req.flush({
  numberOfCandles: 'Test'
});
httpMock.verify();
}));

To my surprise, the test passed. Shouldn't the type check detect that a string was provided instead of a number? Am I missing a step outlined in the documentation? It appears like there is no runtime typechecking going on here. How can I implement this and is it even necessary? Thank you!

Answer №1

TypeScript enforces static typing during the compilation process, but once it is compiled into JavaScript, all type information is removed. This means that at runtime, TypeScript is essentially treated as untyped JavaScript where variables are of type "Object". While some level of property checking can be done through duck typing, there are limited options for type validation during runtime.

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

I need to compile a comprehensive inventory of all the publicly accessible attributes belonging to a Class/Interface

When working with TypeScript, one of the advantages is defining classes and their public properties. Is there a method to list all the public properties associated with a particular class? class Car { model: string; } let car:Car = new Car(); Object. ...

Hosting a web application like it's the main directory in ASP.NET from a subfolder

I am currently developing an Angular 2 application that is hosted on a basic ASP.NET WebApplication. The code for the entire project is bundled up neatly in one folder using webpack. However, whenever I need to redeploy the Angular app, I find myself havin ...

Troubleshooting Angular2 ngFor: Finding a Fix

I'm having trouble setting up a basic shopping list using ngFor in Angular. import { Component, View } from 'angular2/angular2'; @Component({ selector: 'my-app' }) @View({ template: '<h1>{{title}}</h1>< ...

Mocking transitive dependencies in Typescript and Node.js for integration testing: A comprehensive guide

Imagine a scenario where there is an Express route managed by a controller. The controller relies on a service, which in turn uses a repository to interact with a data source. To test this route, one may want to create an integration test using Supertest: ...

Should I use Object.assign or define class properties?

Currently in the process of developing an angular application that interacts with the twitch API. The API returns data in various formats, some of which I need to parse and save into specific classes. My main concern is understanding the potential drawbac ...

Angular 5 APP_INITIALIZER: Provider parse error - Cyclic dependency instantiation not possible

I am utilizing the APP_INITIALIZER token to execute a task upon page load before my Angular application is initialized. The service responsible for this functionality relies on another service located within my CoreModule. The issue at hand seems to be ab ...

How can holidays be incorporated into the Kendo UI scheduler in Angular 6?

Is there a way to incorporate holidays into the Kendo UI scheduler in an Angular 6 project? I have a JSON array containing holiday dates, and during holidays I want to restrict users from adding events. Additionally, I would like the background color to b ...

Angular's Route Guard feature is programmed to redirect users to the home page every time before they

I have been working on implementing a route guard for my website. The guard is responsible for checking the token and returning either true or false. If it returns false, it should redirect to the desired route. However, I am facing an issue where instead ...

Using `rootDirs` in a monorepo setting results in unnecessary subfolders like `src` being generated in the `outDir`

I am in the process of planning a monorepo TypeScript project structured as follows: / (root) +--backend/ | +-src/ | \-tsconfig.json +--shared/ | \-src/ \--frontend/ \-src/ The tsconfig.json file looks like this: { "compil ...

Ways to decrease the space between lines of text within a single mat-option element

https://i.sstatic.net/Sr1cb.png ::ng-deep .mat-select-panel mat-option.mat-option { height: unset; } ::ng-deep .mat-option-text.mat-option-text { white-space: normal; } Currently, I have implemented this code to ensure that text in options wraps to t ...

I need assistance with using the angular-oauth2-oidc library to retrieve data from an asynchronous storage provider and then pass it to a synchronous storage implementation

Typically, the angular-oauth2-oidc library saves tokens in session storage by default. While you can provide your own storage provider through the OAuthStorage class, it requires a storage provider that can retrieve data synchronously. I am developing a ...

How does Typescript handle when an RxJS Observable emits numbers but the observer.next() takes a string?

Imagine having this method within a Typescript/Angular project: subscribeSubject() { const subject = new Subject(); subject.subscribe({ next: (v1: number) => console.log('v1=',v1) }); subject.subscribe({ next: ( ...

Struggling to locate a declaration file for the 'cloudinary-react' module? Consider running `npm i --save-dev @types/cloudinary-react` or exploring other options to resolve this issue

Currently, I am working with Typescript in React. Strangely, when I try to import the following: import { Image } from 'cloudinary-react'; I encounter this error: Could not find a declaration file for module 'cloudinary-react'. ' ...

Eliminate incorrect or invalid state when resetting a dropdown in an Angular ng-select component

I have integrated the ng-select plugin into my Angular project for handling dropdowns. One specific requirement I have is to reset the second dropdown when the first dropdown is changed. Below is a snippet of the code: <ng-select [items]="branchMo ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

Can we deploy the back end of an Angular web application on a port that is visible to the public?

Setting the scene: Currently, my role at a company involves managing an Angular PWA that operates on port 8080. We have also built a Node.js backend, accessible via port 5050. To enable Service Workers functionality, we've applied SSL to both system ...

Retrieving data from an API using VUEJS3 and Typescript

I am facing an issue with displaying data in my template. When I try to do so, the screen remains blank. I am using Vue.js 3 with TypeScript and I am fairly new to this technology. <template> <div> <img :src="datas[0].imag ...

Why don't my absolute paths work on nested folders in React and Typescript?

Struggling to configure absolute paths in my React project, encountering challenges with nested folders and the use of @ prefix. Here's what I have set up in my tsconfig.json: { "compilerOptions":{ "baseUrl":"src", ...

Increasing an ID number automatically using Javascript

I'm currently working on a functionality where a unique number is automatically generated whenever a new record is created. For instance, if I were to click "Create record" on a webpage, the number would auto-fill in the record ID field. Subsequently, ...

What changes do I need to make to my code in order to sort the cards based on their stock levels and prices before rendering them on the webpage?

Currently working on a React application using TypeScript to display cards for a store. The challenge I'm facing involves fetching card data from one API and then retrieving additional information such as stock and price from another API to allow user ...