11.09.2015 Views

Typescript Deep Dive by Basarat Ali Syed

Typescript Deep Dive by Basarat Ali Syed

Typescript Deep Dive by Basarat Ali Syed

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

TypeScript <strong>Deep</strong> <strong>Dive</strong><br />

Classes<br />

The reason why its important to have classes in JavaScript as a first class item is that:<br />

1. People like to use classes<br />

2. Provides a consistent way for developers to use classes instead of every framework (emberjs,reactjs etc) coming up<br />

with their own version.<br />

Finally JavaScript developers can have class . Here we have a basic class called Point:<br />

class Point {<br />

x: number;<br />

y: number;<br />

constructor(x: number, y: number) {<br />

this.x = x;<br />

this.y = y;<br />

}<br />

add(point: Point) {<br />

return new Point(this.x + point.x, this.y + point.y);<br />

}<br />

}<br />

var p1 = new Point(0, 10);<br />

var p2 = new Point(10, 20);<br />

var p3 = p1.add(p2); // {x:10,y:30}<br />

This class generates the following JavaScript on ES5 emit:<br />

var Point = (function () {<br />

function Point(x, y) {<br />

this.x = x;<br />

this.y = y;<br />

}<br />

Point.prototype.add = function (point) {<br />

return new Point(this.x + point.x, this.y + point.y);<br />

};<br />

return Point;<br />

})();<br />

This is a fairly idiomatic traditional JavaScript class pattern now as a first class language construct. Note that constructor<br />

is optional.<br />

Inheritance<br />

Classes in TypeScript (like other langauges) support single inheritance using the extends keyword as shown below:<br />

class Point3D extends Point {<br />

z: number;<br />

constructor(x: number, y: number, z: number) {<br />

super(x, y);<br />

this.z = z;<br />

}<br />

add(point: Point3D) {<br />

var point2D = super.add(point);<br />

return new Point3D(point2D.x, point2D.y, this.z + point.z);<br />

}<br />

}<br />

If you have a constructor in your class then you must call the parent constructor from your constructor (TypeScript will point<br />

this out to you). This ensures that the stuff that it needs to set on this gets set. Followed <strong>by</strong> the call to super you can add<br />

Classes<br />

12

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!