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.

3
  • 2
    Did you import it from @angular/router? Commented Jul 4, 2016 at 8:20
  • @GünterZöchbauer thank you. Commented Jul 4, 2016 at 8:26
  • Weird. Everything else auto imports with VS Code's intellisense, but NavigationEnd won't? Things like ActivatedRoute and Router were imported into @angular/router, but I had to type NavigationEnd in manually. Commented Apr 2, 2023 at 16:29

2 Answers 2

26

Seems you're missing an import

import { Router, NavigationEnd } from '@angular/router'
Sign up to request clarification or add additional context in comments.

3 Comments

Why is Angular2 encourage/forcing this anti-pattern on developers? What value is there in using instanceof to test an Event type?
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 stackoverflow.com/questions/33520043/… is a bit of an improvment.
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?
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 ;-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.