Created
June 13, 2015 15:15
-
-
Save wkronemeijer/71b10cf882125f898161 to your computer and use it in GitHub Desktop.
Creating value types with minimal boilerplate
This file contains 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
// Sometimes you'll need a value type; for representing a point, or other values | |
// which are fully defined after construction. If we take the example of a point: | |
class Point { | |
constructor(public x: number, public y: number) { | |
return Object.freeze(this); | |
} | |
} | |
let p = new Point(3, 4); | |
console.log(p) // ==> Point {x: 3, y: 4} | |
p.x = 20 | |
console.log(p) // ==> Point {x: 3, y: 4} | |
// as you can see, the x and y values of p remain unchanged; any mutation won't cause | |
// an exception, unless you use strict mode. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment