TypeScript
TypeScript Demo
• Basic Types
• Any Type
• Interfaces
• Classes
• Modules
• Generics
• Mixins
var n: number;
var a; // no type -> Any
var s = "Max"; // Contextual typing -> string
n = 5; // valid because 5 is a number
a = 5; // valid because a is of type Any
a = "Hello"; // valid because a is of type Any
n = "Hello"; // compile time error because
// "Hello" is not a number
Type Basics
Any
Primitive Types
Number
Boolean
String
Contextual typing
Determine result type
from expressions
automatically
var person = function (age: number) {
this.age = age;
this.growOld = function () {
this.age++;
alert(this.age);
}
this.growOldL = () => {
this.age++;
alert(this.age);
}
}
var p = new person(1);
setTimeout(p.growOldL, 100);
setTimeout(alert(p.age), 100);
Type Basics
Lambda Function
aka. Arrow function
• Eliminates the needs
for typing function
over and over again.
• Lexically captures
the meaning of this
function getAverage(a: number, b: number, c?: number) {
var total = a + b;
if (c)
total = total + c;
return total;
}
function getAverages(...a: number[]):number {
var total = 0;
for (var i = 0; i < a.length; i++) {
total += a[i];
}
return total;
}
Type Basics
Functions
Optional Parameters
Default Parameters
Rest Parameters
Rest parameters allow
caller to specify zero or
more arguments of the
specified type.
function getTotal(a: string, b: string, c: string): number;
function getTotal(a: number, b: number, c: number): number;
function getTotal(a: number, b: string, c: number): number;
// implementation signature
function getTotal(a: any, b: any, c?: any): number {
var total = parseInt(a, 10) + parseInt(b, 10) + parseInt(c,
10);
return total;
}
var result = getTotal(2, 2, 2);
alert(result);
Type Basics
Functions
• Overloading
interface IStudent {
id: number;
name: string;
onLeave?: boolean;
}
function printStudent(s: IStudent) {
}
// Describing function types
interface searchFunction {
(source: string, subString: string):boolean
}
var searchFunctionImpl: searchFunction = function (s, ss)
{
return true;
}
Type Basics
Interfaces
Interface can be used as
an abstract
type that can be
implemented by
concrete classes, but
they can also be used to
define any structure in
your TypeScript
program.
Interfaces are also
capable of describing
function types.
abstract class A {
foo(): number { return this.bar(); }
abstract bar(): number;
}
// error, Cannot create an instance of the abstract class 'A'
var a = new A();
class B extends A {
bar() { return 1; }
}
var b = new b(); // success, all abstracts are defined
Type Basics
Abstract Classes (v 1.6,
Sept 16th)
Similar in some ways to
interfaces, abstract
classes give you a way
of creating a base class,
complete with default
implementations
class Student {
private name: string;
constructor(name: string, age: number) {
this.name = name;
}
print() {
alert(this.name);
}
}
TODO: Static Types
Type Basics
Classes
TypeScript classes
become JavaScript
pseudo-classes
http://javascript.info/tutorial/pseudo-classical-pattern
Enforcement of private
variables is at runtime
only.
class Animal {
Name: string;
constructor(name: string) {
this.Name = name;
}
move(meters = 0) {
alert(this.Name + " moved " + meters);
}
}
class Snake extends Animal {
}
class MyStudent implements IStudent {
id: number;
name: string;
onLeave: boolean;
}
Type Basics
Types of Class
Heritage
Implements & Extends
There are two types of
class heritage in
TypeScript. A class can
implement an interface
using the implements
keyword
and a class can inherit
from another class using
the extends keyword.
// Internal Modules.
module Shipping {
export interface Ship {
name: string;
tons: number;
}
export class NewShip implements Ship {
name = "New Ship";
tons = 500;
}
}
// Splitting into multiple files.
/// <reference path=“Shipping.ts" />
tsc --out all.js app1.ts
Type Basics
Modules
Gives you various ways
to organize your code in
TypeScript.
1. Internal Modules
2. External Modules
// External Modules.
export class Ship {
name = "New Ship";
tons = 500;
}
// ---------------------------------
import Shipping = require('Ship')
var s = new Shipping.Ship();
// ---------------------------------
tsc --module commonjs app1.ts
tsc --module amd app1.ts
Type Basics
Modules
External Modules
• AMD using RequireJs
• CommonJs
class MyContainer<T> {
private array: T[];
constructor(array: T[]) {
this.array = array;
}
add(item: T) {
this.array.push(item);
}
}
var strContainer = new MyContainer<number>([1]);
strContainer.add(2);
Type Basics
Generics
Gives you the ablility to
create a component that
can work over a variety
of types rather than a
single one.
Generic Constraints
$('#id').html('TypeScript complains that $ is undefined');
Type Basics
Ambient Declarations
Ambient declarations
can be used to add type
information to existing
JavaScript. Commonly,
this would mean
adding type information
for your own existing
code, or for a third-
party library that you
want to consume in
your TypeScript
program.
http://definitelytyped.org/
• http://definitelytyped.org/tsd/
Other Stuff
• Mixins
• Iterators
• Decorators
• Union Types, Type Guards
• Intersection types
• Local type declarations
• ES6 generators
• Asyn/await
AngularJS 1.x + TypeScript
Aurangzaib Siddiqui
End of Part 1

All You Need to Know About Type Script

  • 9.
  • 10.
    TypeScript Demo • BasicTypes • Any Type • Interfaces • Classes • Modules • Generics • Mixins
  • 11.
    var n: number; vara; // no type -> Any var s = "Max"; // Contextual typing -> string n = 5; // valid because 5 is a number a = 5; // valid because a is of type Any a = "Hello"; // valid because a is of type Any n = "Hello"; // compile time error because // "Hello" is not a number Type Basics Any Primitive Types Number Boolean String Contextual typing Determine result type from expressions automatically
  • 12.
    var person =function (age: number) { this.age = age; this.growOld = function () { this.age++; alert(this.age); } this.growOldL = () => { this.age++; alert(this.age); } } var p = new person(1); setTimeout(p.growOldL, 100); setTimeout(alert(p.age), 100); Type Basics Lambda Function aka. Arrow function • Eliminates the needs for typing function over and over again. • Lexically captures the meaning of this
  • 13.
    function getAverage(a: number,b: number, c?: number) { var total = a + b; if (c) total = total + c; return total; } function getAverages(...a: number[]):number { var total = 0; for (var i = 0; i < a.length; i++) { total += a[i]; } return total; } Type Basics Functions Optional Parameters Default Parameters Rest Parameters Rest parameters allow caller to specify zero or more arguments of the specified type.
  • 14.
    function getTotal(a: string,b: string, c: string): number; function getTotal(a: number, b: number, c: number): number; function getTotal(a: number, b: string, c: number): number; // implementation signature function getTotal(a: any, b: any, c?: any): number { var total = parseInt(a, 10) + parseInt(b, 10) + parseInt(c, 10); return total; } var result = getTotal(2, 2, 2); alert(result); Type Basics Functions • Overloading
  • 15.
    interface IStudent { id:number; name: string; onLeave?: boolean; } function printStudent(s: IStudent) { } // Describing function types interface searchFunction { (source: string, subString: string):boolean } var searchFunctionImpl: searchFunction = function (s, ss) { return true; } Type Basics Interfaces Interface can be used as an abstract type that can be implemented by concrete classes, but they can also be used to define any structure in your TypeScript program. Interfaces are also capable of describing function types.
  • 16.
    abstract class A{ foo(): number { return this.bar(); } abstract bar(): number; } // error, Cannot create an instance of the abstract class 'A' var a = new A(); class B extends A { bar() { return 1; } } var b = new b(); // success, all abstracts are defined Type Basics Abstract Classes (v 1.6, Sept 16th) Similar in some ways to interfaces, abstract classes give you a way of creating a base class, complete with default implementations
  • 17.
    class Student { privatename: string; constructor(name: string, age: number) { this.name = name; } print() { alert(this.name); } } TODO: Static Types Type Basics Classes TypeScript classes become JavaScript pseudo-classes http://javascript.info/tutorial/pseudo-classical-pattern Enforcement of private variables is at runtime only.
  • 18.
    class Animal { Name:string; constructor(name: string) { this.Name = name; } move(meters = 0) { alert(this.Name + " moved " + meters); } } class Snake extends Animal { } class MyStudent implements IStudent { id: number; name: string; onLeave: boolean; } Type Basics Types of Class Heritage Implements & Extends There are two types of class heritage in TypeScript. A class can implement an interface using the implements keyword and a class can inherit from another class using the extends keyword.
  • 19.
    // Internal Modules. moduleShipping { export interface Ship { name: string; tons: number; } export class NewShip implements Ship { name = "New Ship"; tons = 500; } } // Splitting into multiple files. /// <reference path=“Shipping.ts" /> tsc --out all.js app1.ts Type Basics Modules Gives you various ways to organize your code in TypeScript. 1. Internal Modules 2. External Modules
  • 20.
    // External Modules. exportclass Ship { name = "New Ship"; tons = 500; } // --------------------------------- import Shipping = require('Ship') var s = new Shipping.Ship(); // --------------------------------- tsc --module commonjs app1.ts tsc --module amd app1.ts Type Basics Modules External Modules • AMD using RequireJs • CommonJs
  • 21.
    class MyContainer<T> { privatearray: T[]; constructor(array: T[]) { this.array = array; } add(item: T) { this.array.push(item); } } var strContainer = new MyContainer<number>([1]); strContainer.add(2); Type Basics Generics Gives you the ablility to create a component that can work over a variety of types rather than a single one. Generic Constraints
  • 22.
    $('#id').html('TypeScript complains that$ is undefined'); Type Basics Ambient Declarations Ambient declarations can be used to add type information to existing JavaScript. Commonly, this would mean adding type information for your own existing code, or for a third- party library that you want to consume in your TypeScript program.
  • 23.
  • 24.
    Other Stuff • Mixins •Iterators • Decorators • Union Types, Type Guards • Intersection types • Local type declarations • ES6 generators • Asyn/await
  • 27.
    AngularJS 1.x +TypeScript Aurangzaib Siddiqui End of Part 1

Editor's Notes

  • #8 Typescript is not a new language. It is at the core JS. It is JS with type annotations, decorators and generic etc. What it adds is type and powered by that is tooling. Tooling that is not possible with dynamic language like JavaScript. So when you compile it all goes away and what you get is simple javascript.
  • #12 ‘Contextual typing‘ is a form of type inference.
  • #13 ‘Contextual typing‘ is a form of type inference.
  • #14 ‘Contextual typing‘ is a form of type inference.
  • #15 In many languages, each overload has its own implementation but in TypeScript the overloads all decorate a single implementation
  • #16 ‘Contextual typing‘ is a form of type inference.
  • #17 ‘Contextual typing‘ is a form of type inference.
  • #18 ‘Contextual typing‘ is a form of type inference.
  • #19 ‘Contextual typing‘ is a form of type inference.
  • #22 interface Lengthwise { length: number; } function <T extends Lengthwise>(arg: T): T { console.log(arg.length); }
  • #23 All ambient declarations begin with the declare keyword. This tells the compiler that the following code block contains only type information and no implementation. Blocks of code created using the declare keyword will be erased during compilation and result in no JavaScript output. declare class jQuery { html(html: string): void; } declare function $(query: string): jQuery; /// <reference path="typings/jquery/jquery.d.ts" />
  • #25 https://github.com/ziaukhan/learn-typescript/blob/master/step16_union_types/app.ts http://blogs.msdn.com/b/typescript/archive/2014/11/18/what-s-new-in-the-typescript-type-system.aspx
  • #26 AtScript