angular - 做什么是指 Typescript 类构造函数参数的前面?
问题描述
我正在阅读Angular - 测试文档。在描述如何测试异步服务<any>
(Testing HTTP services)时,我遇到了一个在传递参数前面带有一个类构造函数。完整的行由下式给出
heroService = new HeroService(<any> httpClientSpy);
我知道,any
在 Typescript 中,字面意思是“任何”类型。guillemets ( <...>
) 是做什么用的?为什么在论点前面打字?它用于类型解析吗?
文档中的完整代码:
let httpClientSpy: { get: jasmine.Spy };
let heroService: HeroService;
beforeEach(() => {
// TODO: spy on other methods too
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
heroService = new HeroService(<any> httpClientSpy);
});
it('should return expected heroes (HttpClient called once)', () => {
const expectedHeroes: Hero[] =
[{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
httpClientSpy.get.and.returnValue(asyncData(expectedHeroes));
heroService.getHeroes().subscribe(
heroes => expect(heroes).toEqual(expectedHeroes, 'expected heroes'),
fail
);
expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
});
it('should return an error when the server returns a 404', () => {
const errorResponse = new HttpErrorResponse({
error: 'test 404 error',
status: 404, statusText: 'Not Found'
});
httpClientSpy.get.and.returnValue(asyncError(errorResponse));
heroService.getHeroes().subscribe(
heroes => fail('expected an error, not heroes'),
error => expect(error.message).toContain('test 404 error')
);
});
解决方案
这是类型断言。
最初添加的语法是
<foo>
.<foo>
但是,在 JSX 中使用样式断言时,语言语法存在歧义。因此,现在建议您仅as foo
用于一致性。
https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html
推荐阅读
- c - after generate the rpc files and try to compile it i get an conflict error
- ios - 过滤CoreData结果 - 列表(UI)不根据过滤结果更新
- google-apps-script - MailApp.send 电子邮件 - 未发送消息/邮件因外部电子邮件 ID 被退回/没有添加在谷歌表格、谷歌表单中工作
- flutter - 我如何在颤振应用程序中解决这个问题
- c++ - 在 C++ 中,派生类(参数比基类多)可以使用基类函数和重载运算符吗?
- django-rest-framework - Django Rest Framework - 更新视图中的 ForeignKey Field 条目
- python - 我正在开发一个有多个页面的 GUI(我使用不同的类来显示不同的页面)。我面临的问题是导航
- hive - 来自容器启动 exitCode=2 的异常,可能与 Flink SQL Hive 连接器有关
- apache-spark - 运行kafka spark流jar时出现spark-submit错误
- r - Plotly - 两种颜色混合为一种颜色,但在使用颜色标签时不应该