Created
September 12, 2018 16:02
-
-
Save santosh/b605b01498b9a05e8f1450ef3ed60c7f to your computer and use it in GitHub Desktop.
Classes and modules in #TypeScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// import syntax is kinda just opposite from Python | |
import {Point} from './point'; | |
let point = new Point(); | |
let x = point.X; | |
point.X = 10; | |
point.draw(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// exporting exposes the class to other files | |
export class Point { | |
// access modifier private, public are by default | |
private x: number; | |
private y: number; | |
// constructor is like __init__ in Python | |
// with ?, it's an optional argument | |
// but with ?, all the param right to that should also be optional | |
constructor(x?: number, y?: number) { | |
this.x = x; | |
this.y = y; | |
} | |
// alternative constructor, which allows to remove line 3-4 on top | |
// constructor(private x?: number, private y?: number) { | |
// } | |
// these are the methods; this is analogous to self in python | |
draw() { | |
console.log("X: " + this.x + ", Y: " + this.y); | |
} | |
// getters and setter are somewhat different in typescript | |
// get and set are reserved keywords | |
// you don't need paren to get or set values | |
get X() { | |
return this.x; | |
} | |
set X(value) { | |
if (value < 0) { | |
throw new Error("Value cannot be less than zero."); | |
} | |
this.x = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment