Ionic 2 syntax error when compiling TypeScript

Following the instructions here , I got to the point of getting a syntax error when compiling my typescript code.

Here is the error:

/app/pages/list/list.js Module build error: SyntaxError: / focus / projects / ionic -todo / app / pages / list / list.js: Unexpected token (10:17) 8 | 9 | export class ListPage {

10 | constructor (nav: NavController) {| ^ 11 | this.nav = nav; 12 | 13 | this.items = [

As you can see, something seems to be wrong with the colon. However, if you remove the colon, you will get a similar error, which instead contains a space.

Here is the complete code:

import {Page, NavController} from 'ionic-angular'; import {AddItemPage} from '../add-item/add-item'; @Page({ templateUrl: 'build/pages/list/list.html' }) export class ListPage { constructor(nav: NavController){ this.nav = nav; this.items = [ {'title': 'hi', 'description': 'hello'}, {'title': 'sadf', 'description': 'asdfasdf'}, {'title': 'asd', 'description': 'asdf'} ]; } addItem() { this.nav.push(AddItemPage, {ListPage: this}); } } 

Any ideas what could be causing this?

+3
javascript angular typescript ionic2
source share
2 answers

Your error allows me to think that you are trying to execute your TypeScript code directly without compiling (preprocessing) or dragging it on the fly.

I think your code should only be ES6. In fact, with ES6 you have class support, but not type support (for example, in the constructor / method).

I looked at the Ionic2 generator templates and they seem to be ES6. See this link:

You can adapt your code as follows:

 import {Page, NavController} from 'ionic-angular'; import {AddItemPage} from '../add-item/add-item'; @Page({ templateUrl: 'build/pages/list/list.html' }) export class ListPage { static get parameters() { return [[NavController]]; } constructor(nav){ this.nav = nav; this.items = [ {'title': 'hi', 'description': 'hello'}, {'title': 'sadf', 'description': 'asdfasdf'}, {'title': 'asd', 'description': 'asdf'} ]; } addItem() { this.nav.push(AddItemPage, {ListPage: this}); } } 
+2
source share

When you write a .js file, you will need to provide a static block ie

 static get parameters() { return [[NavController]]; } 

to get the type nav , which is inside the contructor parameter.

but in the .ts file, you do not need to define a static block, you can just define it inside the constructor, for example:

 constructor (nav : NavController) {} 

you can think of it as nav is a variable and NavController is a type.

This is why you got the error. You used the typescript (. Ts) syntax in the javascript (.js) file.

So, the next time you look at the tutorial, try to find out if the tutor is working with a .js or .ts file :-)

Hope this helps.

0
source share

All Articles