SlideShare a Scribd company logo
Working with TypeScript
Oswald Campesato
Consultant/Training:
www.iquarkt.com
ocampesato@yahoo.com
What is TypeScript?
• Microsoft created TypeScript in October/2012
• Supports ES6
• Supports interfaces and sub-interfaces
• Supports classes and subclasses
• Optional type system
• Angular 2 is written in Typescript
https://scotch.io/tutorials/why-you-shouldnt-be-scared-of-
typescript8
More TypeScript Details
• A compiled language (tsc compiler)
• strong typing and also type inferencing
• type checking during compile time
• "minimal" extra compile time overhead
• tsc transpiles ".ts" files into ".js" files
• [sudo] npm install –g typescript // <- installs “tsc”
Links with TypeScript Details
• Official TypeScript website:
http://www.typescriptlang.org/
• Typings: TypeScript Definition Manager:
https://github.com/typings/typings
Definitely Typed: 3rd-party TypeScript Definitions:
http://definitelytyped.org/
Browser Support for TypeScript
• Browsers support only ECMA5
• TypeScript is transpiled to ECMA5
• ES6 is transpiled to ECMA5
• TypeScript playground:
https://www.typescriptlang.org/play/
• tsc is the TypeScript compiler (can also use Babel)
TypeScript Exposes 9 Types
• Boolean
• Number
• String
• Array
• Tuple
• Enum
• Any
• Void
• Function
Additions to TypeScript
• Types
• Classes
• Annotations
• Imports
• language utilities (e.g. destructuring)
• interfaces
• inheritance
• generics
Simple Types in TypeScript
• var isDone: boolean = false;
• var height: number = 6;
• var name: string = "dave";
• var myList:number[] = [1, 2, 3]; // option #1
• var myList:Array<number> = [1, 2, 3]; // option #2
• var changeMe: any = 4;
• changeMe = ”I’m a string now";
• var myList:any[] = [1, true, ”pizza"];
ECMA5 vs TypeScript Functions
• ECMA5 version:
• function add(a,b) { return a+b; }
• add(1,4); // 5
• add(1,’4'); // 14 (valid in ECMA5)
• TypeScript version:
• function add(a:number, b:number) { return a+b; }
• add(1,4); // 5
• add(1,’4'); // (error in TypeScript)
Functions in TypeScript
• msg is an argument of type string and return type is
void in the myLogger function:
• function myLogger(msg?:string): void {
• console.log("My custom logger: “+msg);
• }
• Note: the trailing question mark (“?”) after msg
indicates that msg is an optional argument
Simple Iteration: Factorial
• factorial(n) {
• var prod = 1;
• for(var i=1; i<=n; n++) {
• prod *= i;
• console.log(“factorial “+i+” = “+prod);
• }
• return prod;
• }
• console.log(“factorial 5 = “+factorial(5));
• console.log(“factorial 10 = “+factorial(10));
Exercises: Iteration
• 1) EvenP: calculate the product of the even integers
between 1 and n
• 2) Prime: check if the positive integer n is prime (its
only divisors are 1 and itself)
• 3) print the primes between 2 and 100
• 4) Goldbach’s conjecture: every even number greater
than 2 can be written as a sum of two odd primes:
write a function to show it’s true up to 100 (use #3)
• 5) use #4 to find even numbers with multiple
solutions, such as 14 (=3+11 = 7+7)
Simple Recursion: Factorial
• factorial(n) {
• if(n <= 1) return 1;
• else return n * factorial(n-1)
• }
• console.log(“factorial 5 = “+factorial(5));
• console.log(“factorial 10 = “+factorial(10));
Tail Recursion: Factorial
• factorial(n, prod) {
• if(n <= 1) return prod;
• else return factorial(n-1, n*prod)
• }
• console.log(“factorial 5 = “+factorial(5,1));
• console.log(“factorial 10 = “+factorial(10,1));
Exercises: Recursion
1) use Euclid’s algorithm to find the GCD of two positive
integers (GCD = Greatest Common Divisor)
Example: GCD(10,24) = 2
2) use #1 to find the LCM of two positive integers
(where LCM = Lowest Common Multiple)
Note: LCM(a,b) = a*b/gcd(a,b)
Example: LCM(10,24) = 120
3) Use recursion to calculate Fibonacci(20)
Generics in TypeScript
• Similar to a generic in other languages:
• function identity<T>(arg: T): T {
• return arg;
• }
•
• // output has 'string' type (explicit/inferred):
• var output = identity<string>("Dave");
• var output = identity("Dave");
tsc: Transpiles TypeScript to ECMA5
• 1) version number:
tsc –version
• 2) compile the TS file app.ts:
tsc app.ts (will generate app.js)
• 3) watch for files changes in app.ts:
a) tsc –-watch app.ts
b) tsc –-watch –out bundle.js app.ts
4) tsc –help lists the available options
Output from tsc --init
• {
• "compilerOptions": {
• "module": "commonjs",
• "target": "es3",
• "noImplicitAny": false,
• "outDir": "built",
• "rootDir": ".",
• "sourceMap": false
• },
• "exclude": [
• "node_modules"
• ]
• } // ‘tsc‘ will now compile all TS files in directory
Sample tsconfig.json for Angular 2
• {
• "version": "1.7.5",
• "compilerOptions": {
• "emitDecoratorMetadata": true,
• "experimentalDecorators": true,
• "target": "es5",
• "module": "system",
• "moduleResolution": "node",
• "removeComments": true,
• "sourceMap": true,
• "outDir": "dist"
• },
• "exclude": [
• "node_modules"
• ]
• }
Compilation with tsc
• 1) create the following class in app.ts:
class MyClass { }
• 2) compile the previous class:
tsc app.ts
• 3) step #2 generates this code in app.js:
var MyClass = (function () {
function MyClass() {
}
return MyClass;
})();
Interfaces in TypeScript (1)
interface IUser {
fname: string;
lname: string;
weight?: number; // optional
}
function displayUser(user: IUser) {
console.log("First name = "+user.fname);
}
Interfaces in TypeScript (2)
interface IUser {
fname: string;
lname: string;
weight?: number; // optional
}
// the following code works correctly:
var aUser =
{fname: "John", lname: "Smith", weight:200};
displayUser(aUser);
ES6 Class versus TypeScript Class
class ES6Class { // ES6 Class
constructor(items) { // no type definition
this.items = items;
}
}
let mye6s = new ES6Class([1,2,3]);
console.log(myes6s.items);
class TSClass { // TypeScript Class
items: string[];
constructor(items: string[]) { this.items = items; }
}
let myts = new TSClass([1,2,3]);
console.log(myts.items);
Classes in TypeScript (1)
class User {
fname: string;
lname: string;
weight: number;
constructor(fname:string, lname:string, weight:number) {
this.fname = fname;
this.lname = lname;
this.weight = weight;
}
fullname():string {
return (this.fname+" "+this.lname+" weighs "+this.weight);
}
}
Classes in TypeScript (2)
var u1:User, u2:User;
u1 = new User("Jane", "Smith");
u2 = new User("John", "Jones");
console.log("user1 = "+u1.fullname());
console.log("user2 = "+u2.fullname());
JSON to a TypeScript Class (1)
var people = [
{fname:"Jane",lname:"Smith",zip:"94043"},
{fname:"John",lname:"Jones",zip:"94539"},
{fname:"Dave",lname:"Starr",zip:"67800"}
]
JSON to a TypeScript Class (2)
class Person {
//unnecessary because constructor specifies “public”:
//fname:string;
//lname:string;
//zip:string;
constructor(public fname:string,
public lname:string,
public zip:string) {
this.fname = fname;
this.lname = lname;
this.zip = zip;
}
}
JSON to a TypeScript Class (3)
var TSPeople = [
new Person("Jane","Smith","94043"),
new Person("John","Jones","94539"),
new Person("Dave","Starr","67800")
];
Implementing TypeScript Interfaces (1)
Interface IRect = {
width: number;
height: number;
perimeter: number;
area: number;
}
Implementing TypeScript Interfaces (2)
class Rectangle implements IRect {
constructor(public width:number,
public height:number) {
this.width = width;
this.height = height;
}
public getArea() { return width*height }
public getPerimeter() { return 2*(width+height) }
}
Implementing TypeScript Interfaces (3)
var rect1 = new Rectangle(5,10);
console.log(“area = “+rect1.getArea());
console.log(“perimeter = “+rect1.getPerimeter());
var rect2 = new Rectangle(12,20);
console.log(“area = “+rect2.getArea());
console.log(“perimeter = “+rect2.getPerimeter());
TypeScript Subclasses
class Square extends Rectangle {
constructor(public side:number, width:number, height:number) {
super(width, height);
this.side = side;
}
area(): void {}
perimeter(): void {}
}
var square1 = new Square(20);
console.log("area = "+square1.getArea());
console.log("perimeter = "+square1.getPerimeter());
Exercises for Interfaces/Classes
1) Define an interface IPerson that contains a first
name, last name, and zip code
2) Create a Person2 class that implements IPerson:
class Person2 implements IPerson { … }
3) Modify IPerson so that it contains an optional
weight property
IDEs for TypeScript
WebStorm IDE (30-day trial)
Visual Studio Code (free and cross-platform)
TypEcs (TypeScript IDE for Eclipse):
http://typecsdev.com/
http://definitelytyped.org/directory/tools.html
TypeScript Versions
• https://github.com/Microsoft/TypeScript/wiki/Ro
admap
• Navigate to website to see list of features for:
• TS 2.1
• TS 2.0
• TS 1.9
• TS 1.8
• TS 1.7
• TS 1.6
Recent/Upcoming Books and Training
1) HTML5 Canvas and CSS3 Graphics (2013)
2) jQuery, CSS3, and HTML5 for Mobile (2013)
3) HTML5 Pocket Primer (2013)
4) jQuery Pocket Primer (2013)
5) HTML5 Mobile Pocket Primer (2014)
6) D3 Pocket Primer (2015)
7) Python Pocket Primer (2015)
8) SVG Pocket Primer (2016)
9) CSS3 Pocket Primer (2016)
10) Angular 2 Pocket Primer (2016)

More Related Content

TypeScript

  • 1. Working with TypeScript Oswald Campesato Consultant/Training: www.iquarkt.com ocampesato@yahoo.com
  • 2. What is TypeScript? • Microsoft created TypeScript in October/2012 • Supports ES6 • Supports interfaces and sub-interfaces • Supports classes and subclasses • Optional type system • Angular 2 is written in Typescript https://scotch.io/tutorials/why-you-shouldnt-be-scared-of- typescript8
  • 3. More TypeScript Details • A compiled language (tsc compiler) • strong typing and also type inferencing • type checking during compile time • "minimal" extra compile time overhead • tsc transpiles ".ts" files into ".js" files • [sudo] npm install –g typescript // <- installs “tsc”
  • 4. Links with TypeScript Details • Official TypeScript website: http://www.typescriptlang.org/ • Typings: TypeScript Definition Manager: https://github.com/typings/typings Definitely Typed: 3rd-party TypeScript Definitions: http://definitelytyped.org/
  • 5. Browser Support for TypeScript • Browsers support only ECMA5 • TypeScript is transpiled to ECMA5 • ES6 is transpiled to ECMA5 • TypeScript playground: https://www.typescriptlang.org/play/ • tsc is the TypeScript compiler (can also use Babel)
  • 6. TypeScript Exposes 9 Types • Boolean • Number • String • Array • Tuple • Enum • Any • Void • Function
  • 7. Additions to TypeScript • Types • Classes • Annotations • Imports • language utilities (e.g. destructuring) • interfaces • inheritance • generics
  • 8. Simple Types in TypeScript • var isDone: boolean = false; • var height: number = 6; • var name: string = "dave"; • var myList:number[] = [1, 2, 3]; // option #1 • var myList:Array<number> = [1, 2, 3]; // option #2 • var changeMe: any = 4; • changeMe = ”I’m a string now"; • var myList:any[] = [1, true, ”pizza"];
  • 9. ECMA5 vs TypeScript Functions • ECMA5 version: • function add(a,b) { return a+b; } • add(1,4); // 5 • add(1,’4'); // 14 (valid in ECMA5) • TypeScript version: • function add(a:number, b:number) { return a+b; } • add(1,4); // 5 • add(1,’4'); // (error in TypeScript)
  • 10. Functions in TypeScript • msg is an argument of type string and return type is void in the myLogger function: • function myLogger(msg?:string): void { • console.log("My custom logger: “+msg); • } • Note: the trailing question mark (“?”) after msg indicates that msg is an optional argument
  • 11. Simple Iteration: Factorial • factorial(n) { • var prod = 1; • for(var i=1; i<=n; n++) { • prod *= i; • console.log(“factorial “+i+” = “+prod); • } • return prod; • } • console.log(“factorial 5 = “+factorial(5)); • console.log(“factorial 10 = “+factorial(10));
  • 12. Exercises: Iteration • 1) EvenP: calculate the product of the even integers between 1 and n • 2) Prime: check if the positive integer n is prime (its only divisors are 1 and itself) • 3) print the primes between 2 and 100 • 4) Goldbach’s conjecture: every even number greater than 2 can be written as a sum of two odd primes: write a function to show it’s true up to 100 (use #3) • 5) use #4 to find even numbers with multiple solutions, such as 14 (=3+11 = 7+7)
  • 13. Simple Recursion: Factorial • factorial(n) { • if(n <= 1) return 1; • else return n * factorial(n-1) • } • console.log(“factorial 5 = “+factorial(5)); • console.log(“factorial 10 = “+factorial(10));
  • 14. Tail Recursion: Factorial • factorial(n, prod) { • if(n <= 1) return prod; • else return factorial(n-1, n*prod) • } • console.log(“factorial 5 = “+factorial(5,1)); • console.log(“factorial 10 = “+factorial(10,1));
  • 15. Exercises: Recursion 1) use Euclid’s algorithm to find the GCD of two positive integers (GCD = Greatest Common Divisor) Example: GCD(10,24) = 2 2) use #1 to find the LCM of two positive integers (where LCM = Lowest Common Multiple) Note: LCM(a,b) = a*b/gcd(a,b) Example: LCM(10,24) = 120 3) Use recursion to calculate Fibonacci(20)
  • 16. Generics in TypeScript • Similar to a generic in other languages: • function identity<T>(arg: T): T { • return arg; • } • • // output has 'string' type (explicit/inferred): • var output = identity<string>("Dave"); • var output = identity("Dave");
  • 17. tsc: Transpiles TypeScript to ECMA5 • 1) version number: tsc –version • 2) compile the TS file app.ts: tsc app.ts (will generate app.js) • 3) watch for files changes in app.ts: a) tsc –-watch app.ts b) tsc –-watch –out bundle.js app.ts 4) tsc –help lists the available options
  • 18. Output from tsc --init • { • "compilerOptions": { • "module": "commonjs", • "target": "es3", • "noImplicitAny": false, • "outDir": "built", • "rootDir": ".", • "sourceMap": false • }, • "exclude": [ • "node_modules" • ] • } // ‘tsc‘ will now compile all TS files in directory
  • 19. Sample tsconfig.json for Angular 2 • { • "version": "1.7.5", • "compilerOptions": { • "emitDecoratorMetadata": true, • "experimentalDecorators": true, • "target": "es5", • "module": "system", • "moduleResolution": "node", • "removeComments": true, • "sourceMap": true, • "outDir": "dist" • }, • "exclude": [ • "node_modules" • ] • }
  • 20. Compilation with tsc • 1) create the following class in app.ts: class MyClass { } • 2) compile the previous class: tsc app.ts • 3) step #2 generates this code in app.js: var MyClass = (function () { function MyClass() { } return MyClass; })();
  • 21. Interfaces in TypeScript (1) interface IUser { fname: string; lname: string; weight?: number; // optional } function displayUser(user: IUser) { console.log("First name = "+user.fname); }
  • 22. Interfaces in TypeScript (2) interface IUser { fname: string; lname: string; weight?: number; // optional } // the following code works correctly: var aUser = {fname: "John", lname: "Smith", weight:200}; displayUser(aUser);
  • 23. ES6 Class versus TypeScript Class class ES6Class { // ES6 Class constructor(items) { // no type definition this.items = items; } } let mye6s = new ES6Class([1,2,3]); console.log(myes6s.items); class TSClass { // TypeScript Class items: string[]; constructor(items: string[]) { this.items = items; } } let myts = new TSClass([1,2,3]); console.log(myts.items);
  • 24. Classes in TypeScript (1) class User { fname: string; lname: string; weight: number; constructor(fname:string, lname:string, weight:number) { this.fname = fname; this.lname = lname; this.weight = weight; } fullname():string { return (this.fname+" "+this.lname+" weighs "+this.weight); } }
  • 25. Classes in TypeScript (2) var u1:User, u2:User; u1 = new User("Jane", "Smith"); u2 = new User("John", "Jones"); console.log("user1 = "+u1.fullname()); console.log("user2 = "+u2.fullname());
  • 26. JSON to a TypeScript Class (1) var people = [ {fname:"Jane",lname:"Smith",zip:"94043"}, {fname:"John",lname:"Jones",zip:"94539"}, {fname:"Dave",lname:"Starr",zip:"67800"} ]
  • 27. JSON to a TypeScript Class (2) class Person { //unnecessary because constructor specifies “public”: //fname:string; //lname:string; //zip:string; constructor(public fname:string, public lname:string, public zip:string) { this.fname = fname; this.lname = lname; this.zip = zip; } }
  • 28. JSON to a TypeScript Class (3) var TSPeople = [ new Person("Jane","Smith","94043"), new Person("John","Jones","94539"), new Person("Dave","Starr","67800") ];
  • 29. Implementing TypeScript Interfaces (1) Interface IRect = { width: number; height: number; perimeter: number; area: number; }
  • 30. Implementing TypeScript Interfaces (2) class Rectangle implements IRect { constructor(public width:number, public height:number) { this.width = width; this.height = height; } public getArea() { return width*height } public getPerimeter() { return 2*(width+height) } }
  • 31. Implementing TypeScript Interfaces (3) var rect1 = new Rectangle(5,10); console.log(“area = “+rect1.getArea()); console.log(“perimeter = “+rect1.getPerimeter()); var rect2 = new Rectangle(12,20); console.log(“area = “+rect2.getArea()); console.log(“perimeter = “+rect2.getPerimeter());
  • 32. TypeScript Subclasses class Square extends Rectangle { constructor(public side:number, width:number, height:number) { super(width, height); this.side = side; } area(): void {} perimeter(): void {} } var square1 = new Square(20); console.log("area = "+square1.getArea()); console.log("perimeter = "+square1.getPerimeter());
  • 33. Exercises for Interfaces/Classes 1) Define an interface IPerson that contains a first name, last name, and zip code 2) Create a Person2 class that implements IPerson: class Person2 implements IPerson { … } 3) Modify IPerson so that it contains an optional weight property
  • 34. IDEs for TypeScript WebStorm IDE (30-day trial) Visual Studio Code (free and cross-platform) TypEcs (TypeScript IDE for Eclipse): http://typecsdev.com/ http://definitelytyped.org/directory/tools.html
  • 35. TypeScript Versions • https://github.com/Microsoft/TypeScript/wiki/Ro admap • Navigate to website to see list of features for: • TS 2.1 • TS 2.0 • TS 1.9 • TS 1.8 • TS 1.7 • TS 1.6
  • 36. Recent/Upcoming Books and Training 1) HTML5 Canvas and CSS3 Graphics (2013) 2) jQuery, CSS3, and HTML5 for Mobile (2013) 3) HTML5 Pocket Primer (2013) 4) jQuery Pocket Primer (2013) 5) HTML5 Mobile Pocket Primer (2014) 6) D3 Pocket Primer (2015) 7) Python Pocket Primer (2015) 8) SVG Pocket Primer (2016) 9) CSS3 Pocket Primer (2016) 10) Angular 2 Pocket Primer (2016)