Pretty similar to java syntax, but types are provided using the ":" notation.
class Turtle {
heading: number;
x: number;
y: number;
}Constructors are always called constructor, and access to class level fields, likewise uses the this. syntax:
constructor(heading: number, x: number, y: number) {
this.heading = heading;
this.x = x;
this.y = y;
}private, protected, and # (enforcing private at runtime, not just compile time) are supported. :)
- Any typescript file can be a launcher.
- No launcher function is needed, in principle you can just write a
console.log()statement, done.
By default, nothing is referenced - not even files in the same folder. To access other classes, an import and and export are needed.
- Export sample, after class end:
export { Turtle };- Import sample, at class start:
import { Turtle } from 'Turtle'Must be "
'" characters, must not include.tsfile extension.
Using object as type is not a good idea, we have no actual type safety, and we cannot access any fields bound to the specific class.
let turtle: object = new Turtle(0, 0, 0);
console.log(turtle.heading);
headingcannot be accessed, becauseobjectdoes not bind to such a field.
Better: use correct type. Everything in same folder is automatically accessible:
let turtle: Turtle = new Turtle(0, 0, 0);
console.log(turtle.heading);