[英]What does <any> mean infront of an Typescript class constructor argument?
I am reading the Angular - Testing documentation.我正在阅读Angular - 测试文档。 When describing how to test asynchronous services (Testing HTTP services) I encountered a class constructor with an
<any>
in front of the passed argument.在描述如何测试异步服务(测试 HTTP 服务)时,我遇到了一个 class 构造函数,在传递的参数前面带有一个
<any>
。 The complete line is given by完整的行由下式给出
heroService = new HeroService(<any> httpClientSpy);
I know, that any
in Typescript stands for literally "any" type.我知道,Typescript 中的
any
代表字面上的“任何”类型。 What are the guillemets ( <...>
) used for? guillemets (
<...>
) 是做什么用的? And why is the typing in front of the argument?为什么在论点前面打字? Is it used for type parsing?
它用于类型解析吗?
The full code from the documentation:文档中的完整代码:
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')
);
});
This is type assertion.这是类型断言。
Originally the syntax that was added was
<foo>
.最初添加的语法是
<foo>
。 However, there is an ambiguity in the language grammar when using<foo>
style assertions in JSX.但是,在 JSX 中使用
<foo>
样式断言时,语言语法存在歧义。 Therefore it is now recommended that you just useas foo
for consistency.因此,现在建议您只使用
as foo
以保持一致性。
https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html
HeroService is being instantiated as a SpyObject HeroService 被实例化为一个 SpyObject
following the structure |Object遵循结构|对象
You can check in the Jasmine documentation您可以查看 Jasmine文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.