8

I have a problem with Typescript compilation. This code returns the error:

error TS2304: Cannot find name 'NavigationEnd'.

How can I make the compiler know about NavigationEnd type? NavigationEnd is angular2 router event type.

this.router.events.subscribe((e) => {e instanceof NavigationEnd ? 
console.log('NavigationEnd'):console.log('Not NavigationEnd')});

I`m using IDE PHPStorm.

sdgluck
  • 24,894
  • 8
  • 75
  • 90
norweny
  • 313
  • 1
  • 3
  • 15

2 Answers2

25

Seems you're missing an import

import { Router, NavigationEnd } from '@angular/router'
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Why is Angular2 encourage/forcing this anti-pattern on developers? What value is there in using `instanceof` to test an Event type? – Aluan Haddad Oct 21 '16 at 16:42
  • I don't use TS myself (only Dart) and in Dart and other languages I know this is no antipattern. Perhaps filter like shown in http://stackoverflow.com/questions/33520043/how-to-detect-route-change-in-angular-2/38080657#38080657 is a bit of an improvment. – Günter Zöchbauer Oct 21 '16 at 17:53
  • 1
    In JavaScript it is a very confusing pattern because it looks like it does in other languages, but it doesn't even have the same kinds of operands. Java : `x instanceof T` -> `x` is a value and `T` is a type; JavaScript : `x instanceof T` -> `x` is a value and `T` is a value; It also couples you to an implementation detail, why should I care that it has a specific prototype? – Aluan Haddad Oct 21 '16 at 18:39
4

I did a small test and it seems that you might have forgotten to include "NavigationEnd" as an import to your project. (Like günter hinted at in the comments)

import { NavigationEnd } from '@angular/router';

After including this, TypeScript no longer complained about it being missing ;-)

Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49