Joseph Jude

Consult . Code . Coach

A beginner's reference guide to TypeScript Language


code . nodejs . tsc

JavaScript is the only way to write cross-platform applications. With JavaScript you can write mobile applications that run on both iOS & Android, applications that run on Mac, Windows, and Linux, and server applications. There is no other language that is this dynamic across all the spectrum of software development platforms.

Yet, ironically, JavaScript was not conceived for scale and complexity of large applications. Server applications can easily go to millions of lines of code. It is hard to maintain large codebases in JavaScript, because it lacks the key concepts used in mature languages such as classes, modules, and interfaces. Importantly, it lacks static types.

Over the history of JavaScript there has been many attempts to modernize JavaScript. The most recent and a successful one is an attempt by Microsoft. TypeScript was introduced in October 2012, after two years of internal development at Microsoft. TypeScript brings all the features lacking in JavaScript. Yet, it does so without abandoning JavaScript. TypeScript is just a superset of JavaScript.

Within a short period, TypeScript has become popular. Google adapted it for Angular2, its front-end UI framework. Ionic adapted Angular-2 for Ionic2, in essence, adapting TypeScript. With a declaration file, you can use TypeScript on top of any of the existing Node.js web frameworks. So now you can use TypeScript to develop server application, mobile applications, and front-end applications.

So what are the benefits TypeScript brings to JavaScript?

  1. TypeScript brings classes, and interfaces thereby bringing object oriented support;
  2. TypeScript adds types to JavaScript, so errors are identified at compile time;
  3. Because TypeScript brings static types, it has become easier to add intellisense and syntax checking to tools and IDEs;
  4. Because of the same reason, it has become easier to refactor large codebase.

These features bring tremendous productivity gains for large teams with large code bases.

Essentials of TypeScript Language

Let us go over the essential features of the TypeScript language.

Comments

As a superset of JavaScript, TypeScript supports both single line and multiline comments.

// this is a single line comment
/* this is a multi line comment.
Multiline comments starts with slash-star and ends with star-slash */

Declaration

In TypeScript you use const to declare a constant and let to declare a variable.

let  name = "TypeScript";
name = "nodejs";
const pi = 3.141;

TypeScript infers type from declaration. In the above example, name is a variable and pi is a constant. Once an identifier has a type, that type can't be changed.

You can also specify the type by writing it after the variable, separated by a colon.

let name: string = "TypeScript";

Basic Types

TypeScript supports all JavaScript types. In addition, it introduces an enumeration type. In this section, we'll see TypeScript datatypes.

Boolean

Boolean variables can hold either a true of false value.

let isDone: boolean = false;

Number

All numbers are floating point values in TypeScript, as in JavaScript. TypeScript supports hexadecimal, decimal, binary and octal literals.

let loc: number = 600;

String

You can use both double quotes (") or single quotes (') to surround string data.

let name = "typescript"
name = "java"

TypeScript supports multiline strings, with backtick(`).

let subject: string = `TypeScript is awesome.
Google adapting a language developed at Microsoft, shows how awesome it is.
`

TypeScript supports template strings, which can have embedded expressions. Embedded expressions take the form, ${expression}. These are useful in cases like mail-merge where you invoke a templated string multiple times with different value for embedded expressions.

let customerName: string = `Harry`;
let invoiceAmount: number = 1500;
let email: string = `Dear ${customerName},
Invoice for ${invoiceAmount} is enclosed.
Thank you.`

Any

When it is impossible to know the type, you can use any.

let userInput: any;
userInput = "any user input"
userInput = 45.3;
userInput = false;

Void

void is absence of type. It is commonly used to indicate that a function does not return a value.

function showWarning(): void {
    alert("This is a warning")
}

Type Assertions

Sometimes you would want to override the inferred type. Then you can use type assertions. There are two forms of type assertion. One is using "angle-bracket".

let name: any = "Bruce Wills";
let nameLen: number = (<string>name).length;

Second form is using "as".

let name: any = "Bruce Wills";
let nameLen: number = (name as string).length;

Type assertions are different from type casting found in other languages. Casting is a runtime operation, whereas assertion is a compile time operation.

Collections

Collections is grouping of multiple elements into a single unit. TypeScript supports two types of collections--array and tuple.

Array

Arrays could be typed or generic.

let cities: string[] = ['delhi', 'chennai', 'mumbai'];
let cities: Array<string> = ['delhi', 'chennai', 'mumbai'];

Tuple

Tuples are used to group fixed number of elements. Their type need not be the same.

let yearBorn: [string, number];
yearBorn = ['julia roberts', 1967];

Enum

Enum gives friendly names to sets of numeric values.

enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
let firstDay: Day = Day.Sunday;

By default, enums begin numbering their members starting at 0. You can override this manually. In fact, you can manually set values for all elements.

enum Day {Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
enum Direction {North = 2, South = 4, East = 6, West = 8};
enum Direction {North = 2, South = 4, East, West}; // East = 5; West = 6

Union

Sometimes you want a variable to be of multiple types. Say a path variable can be either a single string or an array of strings. Then that variable should be of union type.

let path: string[] | string;
path = ['/home', '/home/dropbox'];
path = '/home';

Operators

Arithmetic Operators

The binary arithmetic operators are: +, -, *, /, %, ++, --.

let a = 5;
let b = 4;
let c = 0;
c = a + b; //c = 9
c = a - b; //c = 1
c = a * b; //c = 20
c = a / b; //c = 1.25
c = a % b; //c = 1
c = a++; //c = 6
c = b--; //c = 3

Comparison Operators

The comparison operators are: ==, ===, !=, >, <, >=, <=.

== and === are equality comparison operators. == checks equality of value, like in any language; === checks equality of value and type.

let a = 5;
let b = 4;
let c = false;
let d = 5;

c = a == b; //c = false
c = a === d; //c = true
c = a != b; //c = true
c = a > b; //c = true
c = a < b; //c = false
c = a >= b; //c = true
c = a <= b; //c = false

Logical Operators

The logical operators are: &&, || and !.

&& is a logical AND operator. If both operands are true, then the condition becomes true.

|| is a logical OR operator. If one of the two operands is true, then the condition becomes true.

! is a logical NOT operator. It reverses the state of the operand.

Assignment Operators

The assignment operators are: =, +=, -=, *=, /=, %=

= is a simple assignment operators. Others carry out the operation and then assigns the value.

b += a is equivalent to b = b + a

Control Flow

In this section, we will see decision-making and looping statements.

if ...else

The if-else statement is a decision-making statement. The syntax of the statement is:

if (boolean-expression) {
    statement1
}
else {
    statement2
}

else part of the statement is optional.

ternary operator

This is a simplified, concise if-else statement. It takes the form:

boolean-expression ? statement1 : statement2

let speed = 80;
let isFast = speed > 55 ? true : false

A detailed example would be to find out if the year is a leap year.

let year = 2016

let isLeapYear = ((year % 400) == 0) ? 1 :
                          (((year % 100) == 0)? 0 :
                          (((year % 4) == 0)  ? 1 :
                            0));//default result
alert(isLeapYear)

for loop

Use for loop when you know how many times a task has to be repeated.

var sum = 0;
for (var i = 0; i <= 1000; i++){
    if (i % 3 == 0 || i % 5 == 0){
        sum = sum + i;
    }
}
console.log(sum);

for-of loop

TypeScript introduces a for-of loop (since TypeScript is a superset, you can also use the existing For-in loop) to loop through collections.

let cities: string[] = ['delhi', 'chennai', 'mumbai'];

for (let city of cities) {
    alert(city);
}

switch

The switch statement is an enhanced if-else statement, which is convenient to use if there are many options to choose.

let animal = 'dog';

switch (animal){
    case 'dog':
        alert('dog');
        break;
    case 'cat':
        alert('cat');
        break;
    default:
        alert('none?')
}

while

Use while to execute a task until a given condition is true.

let sum = 0; while (sum <= 5) { sum = sum + 1; }

do...while

do...while is similar to while loop, except that the statement is guaranteed to run at least once.

let sum = 0;
do {
    sum = sum + 1;
} while (sum <= 4)

Functions

In TypeScript you declare functions similar to JavaScript, with type information.

function squareOf(i: number): number {
    return i * i;
};

Return types can be interfered, so we can declare a function like this:

function squareOf(i: number) { return i * i };

In TypeScript, as in JavaScript, functions are first-class citizens. This means we can assign functions to variables, and pass functions as parameters. We can also write anonymous functions. All of these will generate the same JavaScript.

let sqr1 = function sqr (i: number) : number {
    return i * i;
}

// anonymous function
let sqr2 = function (i: number) : number {
    return i * i;
}

// alternate syntax for anonymous function using =>
let sqr3 = (i: number) : number => { return i * i;}

// return type can be inferred
let sqr4 = (i: number)  => { return i * i;}

// return is optional in one line functions
let sqr5 = (i: number) => i * i

Optional and default values

Functions can take optional values. You mention the optional values by using ?: syntax.

function getFullName(firstName: string, lastName?: string) : string {
    if (lastName) {
        return firstName + " " + lastName;
    } else {
        return firstName
    }
}

You can also mention default values for parameters.


function getFullName(firstName: string, lastName: string = "") : string {
    return (firstName + " " + lastName).trim();
}

Classes

TypeScript brings object-oriented approach to JavaScript. Let us consider an example.

Say you are developing a digital library of books. Then you can define a Book class like this:

class Book {
    name: string;
    purchasedYear: number;

    constructor (name: string, purchasedYear: number){
        this.name = name;
        this.purchasedYear = purchasedYear;
    }
}

let Book1 = new Book('7 habits', 2005)

TypeScript also supports sub-classing or inheritance. If you want to extend the digital library to include all assets like CDs, PDFs and so on, you can modify the above class into a super-class and many sub-classes.

class Asset {
    name: string;
    purchasedYear: number;

    constructor (name: string, purchasedYear: number){
        this.name = name;
        this.purchasedYear = purchasedYear;
    }
}

class Book extends Asset {
    constructor (name: string, purchasedYear: number) {
        super(name, purchasedYear)
    }
}

let book1 = new Book('7-habits', 2013);

Interfaces

Interfaces allow multiple objects to expose common functionality. By using interface, you can enforce that all these assets implement a common functionality, say name, purchased year, and age. Interface is only a contract, implementation is carried out at the classes level.

interface iAsset {
    name: string;
    purchasedYear: number;
    age: () => number;
}

class Book implements iAsset{
    name: string;
    purchasedYear: number;

    constructor (name: string, purchasedYear: number){
        this.name = name;
        this.purchasedYear = purchasedYear;
    }
    age() {
        return (2016 - this.purchasedYear);
    }

}

let Book1 = new Book('7 habits', 2005)
alert(Book1.age)

Final Words

TypeScript is a layer on top of JavaScript targeting developer's productivity. It doesn't improve other aspects of software development using JavaScript, like building a single binary or deployment.

Since TypeScript is a super-set of JavaScript, you can start using TypeScript now, without any alteration to the existing code.

If you are starting a new project in JavaScript, you should really use TypeScript.

Further Reading

TypeScript Handbook
Learn X in Y Minutes, where X = TypeScript
52 technologies in 2016


Like the post? Retweet it. Got comments? Reply.

A beginner's reference guide to #typeScript Language by @jjude: https://t.co/oqAx9jXDce

— Joseph Jude (@jjude) September 28, 2016
Share this on: Twitter / /

Comments

comments powered by Disqus