Cooking Typescript

Typescript is there for a while but it is now gaining popularity because of Angular2 and NativeScript.

ES6 and ES7 are upcoming versions of JavaScript. Right now they are not available in all web browsers. But those have some amazing features which we want to use with our applications.

Transpiler is the term using these days. Transpilershey will convert your code to browser understanding code. That means you can write your code in once language which will be converted into javascript.

Typescript is a superset of ES6,ES5, and ES3. Which means any JavaScript code is valid TypeScript code. In order to use TypeScript in your web browser, you must first compile your code into ES5 to run in the most browser. One nice feature about TypeScript is when all browsers are ready to understand ES6 you can use the same code base to compile into ES6 code.

One of TypeScript's primary features is adding types. Having type information is doing less programming errors.

Ok, Enough. Let's see some features of Typescript.

Before we began to make sure you have installed Node and typescript compiler on your machine. To install typescript just type following command.

npm install -g typescript  

To use typescript

tsc test.ts --watch  

--watch will watch for file changes

We will discuss some features that are only available in TypeScript. Those are...

  • Types
  • Interfaces
  • Decorators

Types

Many people don't know but JavaScript have a type but it does. Those are duck types. That means programmer doesn't need to think about them. Javascript automatically assigns the type to a variable based on the assigned value. Since Typescript is the superset of JavaScript all JavaScript types are there in TypeScript too.

  • boolean
  • number
  • string
  • [] (Array of basic datatype)
  • {} (Object)
  • undefined
  • null

Along with these types also have

  • enum (enumration like {TextBox, Radio, CheckBox})
  • any (use any type)
  • void (nothing)
  • Custom DataTypes (classes and Interfaces)

To define a variable with type.

let isDone: boolean = false;  
let age: number = 6  
let name: string = 'aravind'  
let kids: number[] = [1,2,3] or  
let kids: Array<number> = [1,2,3]  

Some cases we may want to have two datatypes for single varible we can do that by

let isDone:number | boolean;  

Function parameters Types

To pass parameters to a function in TypeScript

function logger(msg:string){  
   // code
}

It's quite common for functions to take optional parameters in JavaScript.

function logger(msg:string, isDebug?:boolen){  
  //code
}

using ? lets typescript compiler to know that isDebug is an optional parameter.

Classes as Types

Typescript treats class es as their own types.

class Animal {name:string};  
class WildAnimal {  
    constructor(animal:Animal){
        // code
    }
}
let tiger = new WildAnimal(new Animal());

like functions classes sometimes have optional members.

class Person {  
    firstName: string;
    middleName?: string;
    lastName: string;
}

Interfaces

One big disadvantage of using classes as Type is they end up creating ES5 code while transpiling. Also, Interfaces are an awesome concept in typescript which enables us to define code contracts for our code. Angular2 uses interfaces through out its framework.

Let's convert our Person Class to an Interface.

interface IPerson {  
   firstName: string;
   middleName?: string;
   lastName: string;
}

I is not mandatory it's just an old code convention.

To implement the interface we will do something like this.

let person:IPerson = {  
    firstName: 'aravind',
    lastName: 'buddha'
}

we don't have to use explicit implements keyword instead of that we will use typescripts type assessing syntax to implement the interface for variables. In above example, if the person object doesn't have firstName or lastName typescript compiler will through an error. If you are using VScode editor you can see the error itself while you are coding.

Ok, In above example, we can use IPerson as a custom data type and we can use them for function parameters, right? In Javascript function parameter could be a function so how can we implement that. Let's see.

interface Callback {  
  (err:string):void;
}

function getLog(callback:Callback) {  
    callback('Error! Custom error.');
}
// function call
getLog((err) => {  
    console.log(err);
});

Callback is an interface with function signature in it. The callback function expects a parameter of type string and returns nothing so we used undefined.

Tip: In Javascript by default undefined returns but in typescript, we should use void because it's more appropriate.

Interface with classes

The interface acts as code contracts. That means it will enforce to build code in a certain way. Let's take an example. If 10 developers are working on a very large scale application. Let's say there an object person on which everyone has to work. One developer may implement it as.

let person = {  
    firstName:'string1',
    lastName: 'string2'
}

other may have done it as

let person = {  
    fName:'string1',
    lName: 'string2'
}

This is a big problem. In order to solve this, we can first define an interface and ask the developer to use them.

interface IPerson {  
    first_name:string
    last_name: string
};

class Student implements IPerson {  
    first_name = 'aravind';
    last_name = 'buddha';
}

Don't confuse with the implements keyword here. We should use it with classes not with variables and functions.

Decorators

This is one of my favorite feature in TypeScript. Decorators are the proposed feature for ES7 but Typescript has already implemented because Anular2 wants to use it in the framework. Java and C# have similar feature call annotations.

Basically, Decorators are nothing but functions with we invoke with prefix @ symbol. Decorators decorates

  • class
  • parameters
  • method
  • property.

If you ever tried angular 2 before. You wold notice

@Component()

Notice that () on @Component this means @Component is called once JavaScript encounters.

Let's write a small example.

function Overwrite(label:string) {  
    return (target: Object, key: string) => {
        Object.defineProperty(target,key,{
            configurable:false,
            get: () => label
        });       
   };   
}

class Person {  
    @Overwrite('aravind')
    name:string = 'test';
}

let p = new Person();

console.log(p.name); // will print aravind insted of test

Here we have a property decorator. Even thought test is been assigned when we print p.name we will get aravind. The Overwrite decorator will take input and use it to decorate our property.

I will discuss more decorators in upcoming tutorials.

Conclusion:

So far we discussed are the features which are used in angular 2 through out its framework. Without understanding these understanding angular 2 is bit difficult. Besides, there are so many other features also available in TypeScript.

I hope this tutorial was helpful to you, leave a comment if you have any questions. For more information.

http://typescriptlang.org

Get posts by email

Like what you're reading? Get these posts delivered to your inbox.