Search code examples
angulartypescripttyping

What does <any> mean infront of an Typescript class constructor argument?


I am reading the Angular - Testing documentation. When describing how to test asynchronous services (Testing HTTP services) I encountered a class constructor with an <any> in front of the passed argument. The complete line is given by

heroService = new HeroService(<any> httpClientSpy);

I know, that any in Typescript stands for literally "any" type. What are the guillemets (<...>) used for? 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')
  );
});

Solution

  • This is type assertion.

    Originally the syntax that was added was <foo>. However, there is an ambiguity in the language grammar when using <foo> style assertions in JSX. Therefore it is now recommended that you just use as foo for consistency.

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