LearningTypescript



LearningTypescript

0 1


LearningTypescript

A demonstration of the benefits of Typescript

On Github bryanerayner / LearningTypescript

Learning Typescript

Or, an appeal to embrace typed languages

Created by Bryan E Rayner

Why not just Javascript?

Javascript, for all it's benefits, provides a considerable challenge for many developers.

  • The bad parts
  • Foreign concepts (prototypes)
  • Perceived language limitations
  • Lack of strong IDE support
  • Preference for different syntax (Ruby)

Alternatives

There are many languages which compile to Javascript:

  • Coffee Script
  • Traceur (ES6 compiler)
  • Clojurescript
  • Dart
  • Typescript

Today, we'll be focusing on Typescript.

Why Typescript?

Typescript is a language which compiles to well-written Javascript.

Hello World (with classes)

// Typescript
class Welcomer
{
  message:string = '';

  setMessage(newMessage:string) {
    this.message = newMessage;
  }

  sayMessage() {
    console.log(this.message);
  }
}

Javascript output

//Javascript
var Welcomer = (function () {
  function Welcomer() {
    this.message = '';
  }

  Welcomer.prototype.setMessage = function (newMessage) {
    this.message = newMessage;
  };

  Welcomer.prototype.sayMessage = function () {
    console.log(this.message);
  };
  return Welcomer;
})();

Familiar syntax

All Javascript is valid Typescript

// Valid Typescript:
var hello = function(){
  return "Hey y'all!";
};

var object = {
  normal:'property',
  definitions:'you bet'
};

console.log(hello());

ES6 features - today

Typescript compiles ES6 syntax to ES5, and ES3

  // Fat arrow functions:
  var boundLookup = (propName) => this[propName];

  // Splat operator
  var splattedFunction = function(one, two, ...rest){
      // rest is the rest of the arguments after two
  }

Plus... Types

Typescript optionally gives developers strong typing.

	// Without types
	var foo = 'five';
	foo = 5; // What if you don't catch this bug?

	// With types
	var bar: string = 'six';
	bar = 6; // This will throw an error in the compiler.

Why Types?

Type systems help you help yourself

  • Errors caught at compile time - not run time
  • IDE refactoring support
  • Increased team cohesion

What is a type?

Type systems tell computers what the heck you're doing.

They help translate this:

var boxCounter = 5;

To this value in RAM:

00000101

As opposed to this ASCII value:

00110101

Strong / Weak types

Here's Javascript and C++ in a quick comparison

    // Javascript:
    var counter;          // Allocate an arbitrary amount of RAM.
    counter = 5;          // Store a value of 5.
    counter = 'cinco';    // Store an array of 16-bit Unicode Characters.

    // C++:
    long counter;         // Allocate 64 bits of RAM.
    counter = 5;          // Store a value of 5
    counter = 'no bueno'; // This code won't even work

Objections to Static Types

  • "Type systems add complicated syntax to my code"
  • "It takes longer for me to write code in C++, Java, etc..."
  • "Compilation is premature optimization, therefore, the root of all evil."

Best of Both Worlds

  • Typescript runs on Javascript - types are optional
  • Types are checked by using 'Duck Typing'
  • You still get compiler errors - if you want them

Plus - IDE Support

Valid Javascript

// Perfectly valid (and insane) Javascript:
  var object = {};
  var summary = 'The fruit bowl has ';

  object.value = function () {
    return summary + 'apple';
  }

  object['value'] = object.value() + "s and oranges.";

  object.value = (function() {
    return object.value + ' And bananas.';
  })();

  summary = (function() {console.log(object.value);})();
// Outputs: 'The fruit bowl has apples and oranges. And bananas.

Compilers be like:

Interfaces

Interfaces tell IDE's (and Typescript) what to expect

// Duck interface
interface Duck {
  age: number;
  name: string;
  secretIdentity: string;

  walk(distance:number): void;
  fly(destination:string) : void;
  quack(volume: number): void;
}

Sort of like free documentation!

Generic Types

For a typical SPA, we might see something like this:

interface Resource<T> {
	route: string;
	get(): T;
	post(value:T): boolean;
	put(values: any): boolean;
	delete(value: T): boolean;
}

Implementing Generics

<T> represents a generic type. It gets defined as you use it.

  interface Chicken{
    id: number;
    name: string;
    breed: string;
    weight: number;
  }

  class ChickenResource implements Resource<Chicken>
  {
    route: string;
    get(): Chicken;
    post(value:Chicken): boolean;
    put(values: any): boolean;
    delete(value: Chicken): boolean;
  }

Demo Time!

Let's implement a Graph API in Typescript

Graphs:

Graph's are a data structure which model connections

  • Facebook
  • Google Search Results
  • Road Maps
  • Concordances

Interfaces:

Node (Data Point)

  interface INode<T>
  {
    // Returns a unique identifier
    _getUId:()=>string;

    // Returns the node data
    _getData:()=> T;
  }

Graph:

  interface IGraph<T>
  {
    _uid:string;
    nodesCount:number;

    addNode(newNode:INode<T>): void;

    addEdge(v: INode<T>, w: INode<T>): void;

    getAdjacentNodes(v: INode<T>): INode<T>[];
    countVertices(): number;

    getNode(id:string): INode<T>;

    //... Plus more goodies...
  }

Demo:

Concordance of Ephesians

Typescript and Teamwork

Typescript adds incredible benefit to team projects:

  • Standard syntax for common patterns
  • Code hinting provided by IDEs
  • 'Jump to definition' support
  • 'Contracts' help define API - Built in documentation!

Let's do some 'work'

For this demonstration, we'll add some functionality to a Graph API.