简体   繁体   English

在Angular 4中对HTTPClient请求进行类型检查

[英]Typechecking HTTPClient request in Angular 4

I wonder how to correctly use the HTTP Client in Angular 4 in regards to type checking. 我想知道如何在Angular 4中正确使用HTTP客户端进行类型检查。 The official documentation under https://angular.io/guide/http says I should do it similar like this: https://angular.io/guide/http下的官方文档说我应该像这样做:

So we have a Cake: 因此,我们有一个蛋糕:

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

and a CakeService: 和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. TypeScript是静态键入的,以进行编译。 After the TypeScript is compiled, it just becomes regular JavaScript which is untyped. 编译TypeScript后,它变成未类型化的常规JavaScript。 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. 但是除此之外,运行时没有更多内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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