Im new in Typescript. I like the idea that the compiler will most likely point out errors because it really gets the code. Now I have done a test project, no compiler errors, but an exception at runtime:
Uncaught ReferenceError: Boat undefined (anonymous function) @ Main.ts: 7
Obviously, imports do not work. But why? I tried with amd and with commonjs and got the same error.
Here is the code:
index.html
<!DOCTYPE html> <html> <head> <title>TypeScript Test</title> <script data-main="main" type="text/javascript" src="require.js"></script> </head> <body> <span id="output"></span> </body> </html>
Main.ts
///<reference path='Vehicle.ts'/> ///<reference path='Car.ts'/> ///<reference path='Boat.ts'/> var outputElement = document.getElementById('output'); var vehicleOne: Vehicle.Vehicle = new Boat.Boat("One"); var car: Car.Car = new Car.Car("Two"); var vehicleTwo: Vehicle.Vehicle = car; outputElement.innerHTML = vehicleOne.do() + " " + vehicleOne.getName() + "<br />" + vehicleTwo.do() + " " + vehicleTwo.getName() + "<br />" + car.do() + " " + car.getName() + " " + car.doCar() + "<br />";
Vehicle.ts
module Vehicle{ export class Vehicle { private name: string; constructor (name: string) { this.name = name; } do() : string { return "Im a vehicle"; } getName() : string { return this.name; } } }
Car.ts
///<reference path='Vehicle.ts'/> module Car { export class Car extends Vehicle.Vehicle { constructor(name:string) { super("CAR: " + name); } do():string { return "Im a car"; } doCar():string { return "Only cars can do this :)"; } } }
Boat.ts
///<reference path='Vehicle.ts'/> module Boat { export class Boat extends Vehicle.Vehicle { constructor(name:string) { super("BOAT " + name); } do():string { return "Im a boat"; } } }
I use Webstorm, the compiler does not output errors, and * .js and * .map.js files are created. There is no way out in the browser. Only the console prints "Uncaught ReferenceError: Boat undefined (anonymous function) @ Main.ts: 7"
Why is this an exception? How to import classes correctly?
javascript oop class webstorm typescript
Moritz gΓΆckel
source share