TypeScript main features handbook

Important keywords and operators

  • class - container for members such as properties and methods
    • complex types
  • constructor - provides initialisation functionality in a class
  • exports - export a member from a module
  • extends - extend a class or interface
  • implements - Implements an interface
  • imports - Import a module
  • interface - Define code contract that can be implemented by types
  • module/namespace - Container for classes and other code
  • public/private - Member visibility modifiers
  • ... - REST parameter
  • => - Arrow functions
  • <typename> - <> characters used to cast/convert between types
  • : - Separator between variable/parameter name and types
  • declare - Ambient declaration

Grammar

Functions

In TS, define a function signature and return type using

1
2
3
4
(a: string) => string

// (a: string) - parameter type
// => string - return type of function

after function name and before writing function statement

1
2
3
4
const init: (a:string, b:string, c:string) => string = function(a, b, c) {
    console.log(a, b, c);
    return a + b + c;
}

Keyword explanations

declare

Ambient declaration used to define avariable ko, we pulled definition file(typings for knockout)

1
2
3
4
// example of adding knockout using ambient declaration

/// <reference path="typings/knockout-2.2.d.ts">
declare var ko: KnockoutStatic;

Types

1. any

any

When we can’t figure out what the type would be, it would any

1
2
3
var data: any;
// OR
var info;

2. Primitive types

number

1
2
3
var age: number = 2;
var score: number = 98.25;
var rating = 98.25;

boolean

1
2
var hasData: boolean = true;
var isReady = true;

string

1
2
var firstName: string = 'Foo';
var lastName = 'bar';

null

null type is something you can use on any of the primitive types.

1
2
3
4
var num: number = null;
var str: string = null;
var isHappy: boolean = null;
var customer: {} = null;

null type is a subtype of all primitives, except for void and undefined

undefined

1
2
var quantity: number;   
var company = undefined;

undefined type is a subtype of all primitives.

3. Arrays and Indexers

1
2
3
4
var names: string[] = ['John', 'Dan'];

var firstName: string;
firstName = names[0];   // string

4. Object Types

Object literals

1
2
3
4
5
6
var square = { h: 10, w: 20 };

var points: Object = { x: 10, y: 20 };

var point2: {};
point2 = { x: 10, y: 20 };

Functions

1
2
3
var multiply = function (x: number) {
  return x * x;
};
1
2
3
4
var multiplyMore: Function;
multiplyMore = function (x: number) {
  return x * x;
};
1
2
3
4
5
6
var squareIt = function (rect: { h: number; w?: number }) {
  if (rect.w === undefined) {
    return rect.h * rect.h;
  }
  return rect.h * rect.w;
};
1
2
// Arrow functions
var myFunc = (h: number, w: number) => h * w;

Class

Class is a container, its role is javascript/typescript is to just encapsulate a code such as functions or variables into reusable containers that can be used thoughout the application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Car {
  // Fields
  /*
    variables that we can put in a class
  */

  // Constructor
  /*
    used to initialize an object. You might pass some started data that the object needs at runtime
  */

  // Properties

  // Functions
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Car {
  // Fields
  engine: string;

  // Constructor
  constructor(engine: string) {
    this.engine = engine;
  }

  // Shorthand way
  class Car {
    // instead of defining field explicitly. We can just use public keyword in front of the variable name and typescript will generate that field for us.
    constructor(public engine: string) { }
  }
}

complex type

1
2
3
4
5
6
7
8
9
10
11
class Engine {
  constructor(public horsePower: number,
              public engineType: string) { }
}

class Car {
  // Engine here is a complex type - using class inside a class
  private _engine: Engine;

  constructor (engine: Engine) { }
}

Casting types <>

1
2
3
4
// cast HTMLElement to HTMLTableElement
var table: HTMLTableElement = <HTMLTableElement>document.createElement('table');

// document.createElement('table'); returns HTMLElement

typescript knows about these (HTMLTableElements or HTMLInputElement) by Type Definition Files

Type Definition Files

Extending Types

Way of achieving inheritance in typescript. We need to use extends keyword.

1
2
3
4
5
6
7
class ChildClass extends ParentClass {
  // constructor is optional
  constructor() {
    // use super() to call the base class's constructor
    super();
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Engine {
    constructor(public horsePower: number, public engineType: string) { }
}

class Auto {
    engine: Engine;

    constructor(engine: Engine) {
        this.engine = engine;
    }
}

class Truck extends Auto {
    fourByFour: boolean;

    constructor(engine: Engine, fourByFour: boolean) {
        super(engine);

        this.fourByFour = fourByFour;
    }
}

Interfaces

Interfaces are the code contracts. They are defined by using the TypeScript keyword called interface

Creating an interface

1
2
3
4
interface IEngine {
  start(callback: (startStatus: boolean) => void): void;
  stop(c allback: (stopStatus: boolean) => void): void;
}
1
2
3
4
5
6
7
8
interface IAutoOptions {
  engine: IEngine;
  basePrice: number;
  state: string;
  make?: string;
  model?: string;
  year?: number;
}

Using an interface

Interfaces can be used on classes as well as in classes.

1. Implementing an interface

interface is implemented in a class by using a keyword called implemnents

Class Engine implements IEngine interface, which means Engine class should have start and stop methods

1
2
3
4
5
class Engine implements IEngine {
  constructor(public horsePower: number, public engineType: string) {}


}

2. Using an interface as a Type

1
2
3
4
5
6
7
8
9
10
class Auto {
  engine: IEngine;
  basePrice: number;
  // and so on...

  constructor(data: IAutoOptions) {
    this.engine = data.engine;
    this.basePrice = data.basePrice;
  }
}

Extending an interface

Using extends keyword

1
2
3
4
5
6
7
8
interface IAutoOptions {
  engine: IEngine;
  basePrice: number;
  state: string;
  make?: string;
  model?: string;
  year?: number;
}
1
2
3
4
interface ITruckOptions extends IAutoOptions {
  bedLength?: string;
  fourByFour: boolean;
}

Modules

Help in keep separation in our code. Use module keyword to declare a module. Prevent global namespace from getting polluted.

1
2
3
4
// Explicitly declare a module
module dataService {
  // code  
}

Internal vs External modules

| Internal Modules | External Modules | | ———– | ———– | | Namespace-like modules | Separately loadable modules | | For grouping code | Exported modules can be imported into other modules | | No need to import them | Need to import
import model = require('/models'); | | Uses CommonJS or AMD conventions | Sequence of loading files is important | Can be loaded in any sequence |

1. Named modules or internal modules

We need to export a class from a namespace so that it can be used outside.

module keyword has been replaced with namespace in TypeScript 1.5 ```ts namespace Shapes { export class Rectangle { constructor(public height: number, public width: number) {} } }

var rect = new Shapes.Rectangle(2,4);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
This code gets converted to an `IIFE`, which is using the concept of module pattern or revealing module pattern.

```js
// equivalent JS
"use strict";
var Shapes;
(function (Shapes) {
    var Rectangle = /** @class */ (function () {
        function Rectangle(height, width) {
            this.height = height;
            this.width = width;
        }
        return Rectangle;
    }());
    Shapes.Rectangle = Rectangle;
})(Shapes || (Shapes = {}));
var rect = new Shapes.Rectangle(2, 4);

Extending named modules

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
namespace Shapes {
  export class Rectangle {
    constructor(public height: number, public width: number) {}
  }
}

var rect = new Shapes.Rectangle(2,4);

// just by using the same name
namespace Shapes {
  export class Square {
    constructor(public height: number, public width: number) {}
  }
}

var sq = new Shapes.Square(2,4);

Separating internal modules

  • Modules separated across files
  • Must load them in proper order sequence
1
2
3
4
5
6
// shapes.ts
namespace Shapes {
  export class Rectangle {
    constructor(public height: number, public width: number){ }
  }
}
1
2
3
4
5
6
// shapemaker.ts
/// <reference path="shapes.ts" />

namespace ShapeMaker {
  var rect = new Shapes.Rectangle(2, 4); 
}

2. External modules

AMD

  • Manage dependencies
  • Loads modules in sequence based on the defined dependencies To use AMD we need to use require.js
-->