Introduction to Typescript

Pankaj Pralhad Parkar

(TSS Consultancy PVT LTD.)

Twitter: @pankajparkar

Facebook: fb.com/pankaj.parkar

LinkedIn: https://in.linkedin.com/in/pankajparkar

Email: parkarpankaj3@gmail.com

Who am I?

What we are going to cover?

  • What is Typescript?
  • Why should I use Typescript?
  • How it works?
  • How to use it?

  • Demo

  • Typescript Fundamentals

What is Typescript?

Typescript is a typed superset of Javascript that compiles to plain Javascript. Any Browser.

Any host. Any OS. Open Source.

Whats wrong with JavaScript?

Javascript has dynamic typings.

Good

  • Variable can hold any type object value.
  • Types are determined on the fly.
  • Implicit type conversion.(eg. string to number)

Bad

  • Difficult to ensure which method should return which type without writing test. 
  • Not all devs use === 
  • Implicit type conversion.

Code without Javascript patterns.

Code with Javascript patterns or Typescript.

Developer moving from server-side to client-side

.Net

Java

Ruby

PHP

- The TypeScript type system​

     

- Your JavaScript is TypeScript

- Types inference

     

- Types are structural using classes/interface

- Type errors do not prevent JavaScript emit

 

 

 

- Types can be ambient

Why Typescript?

var name: Type = 'Value';
var myVariable = '123';
var foo = 123;
foo = '456'; // Error: cannot assign a `string` to a `number`

// Still it compiles to below
var foo = 123;
foo = '456';

How Typescript works?

Typescript file(.ts)

Typescript Compiler

(uses tsconfig.json)

Javascript file(.js)

How to use Typescript?

  1. You could directly install Visual Studio Plugin on VS2013 & VS2015
  2. Install it from npm using below command

npm install -g typescript

 

  • Then convert typescript by using tsc command
  • Use tsconfig.json to configure typescript compiler options.

Other way is, you could go on typescript playground

http://www.typescriptlang.org/play/

Demo

Fundamentals of Typescript.

  1. Classes
  2. Functions
  3. Interfaces
  4. Module & Namespaces
  5. Generics
  6. Enums

Types

  • Boolean
  • string
  • Array
  • Tuple
  • Enum
  • Any
  • void

Classes

  • Traditional JavaScript uses functions and prototype-based inheritance to build up reusable components.
  • Classes provide a way to define function, and it helps to implement prototypal inheritance
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

Inheritance using Classes

class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}
class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        super.move(distanceInMeters);
    }
}
class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 45) {
        super.move(distanceInMeters);
    }
}

Functions

  • Traditional JavaScript uses functions and prototype-based inheritance to build up reusable components.
  • Classes provide a way to define function, and it helps to provide implement prototypal inheritance
let add = (x: number, y: number): number => { 
   return  x + y; 
};
add(1, 2);

Interface

By using Interface you can focus type-checking on the shape of object.

interface SquareConfig {
    color?: string;
    width?: number;
}

let newSquare: SquareConfig = {
   color: "white", 
   area: 100
};

Module & Namespaces

Module

Modules are declarative; the relationships between modules are specified in terms of imports and exports at the file level. 

export interface StringValidator {
    isAcceptable(s: string): boolean;
}

export const numberRegexp = /^[0-9]+$/;

export class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}

Module & Namespaces

Namespaces

Namespace has collection of modules where we can architect our application architecture.

namespace Validation {
    export interface StringValidator {
        isAcceptable(s: string): boolean;
    }

    const lettersRegexp = /^[A-Za-z]+$/;
    const numberRegexp = /^[0-9]+$/;

    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }

    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}

Generics

Flexible Typing

function loggingIdentity<T>(arg: T): T {
    console.log(typeof T)
    console.log(arg.length);  // Error: T doesn't have .length
    return arg;
}

Enums

Flexible Typing

enum Language {
    Java,
    CSharp,
    Javascript
}

// Sample usage
var language = Language.Java;

// Error `string` is not assignable to type `Language` 
// Safety
language = "not a member of card suit"; 

Alternative to Typescript

  • Use pure javascript
  • Use javascript patterns.

Thank You

Q & A

Introduction to Typescript

By Pankaj Parkar

Introduction to Typescript

  • 1,478