简体   繁体   中英

Typechecking HTTPClient request in Angular 4

I wonder how to correctly use the HTTP Client in Angular 4 in regards to type checking. The official documentation under https://angular.io/guide/http says I should do it similar like this:

So 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); } } 

That looks simple. So I wrote a test to see how it works:

 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 suprise, the test passes. Shouldn't the type check catch a string was sent instead of a number? Is there a step I am missing here in the documentation? It looks to me like this does not do typechecking at runtime. How can I achieve this and does it make sense? Thanks!

TypeScript is statically type up to compile time. After the TypeScript is compiled, it just becomes regular JavaScript which is untyped. So at runtime, it cannot fail based on different types, since their both considered "Object" types. Now you can do some kind of duck checking to ensure the proper properties are present. But aside from that, there isn't much more at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM