首页 > 解决方案 > 做什么是指 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')
  );
});

标签: angulartypescripttyping

解决方案


这是类型断言。

最初添加的语法是<foo>. <foo>但是,在 JSX 中使用样式断言时,语言语法存在歧义。因此,现在建议您仅as foo用于一致性。

https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html


推荐阅读