Why TypeScript

Like any other language, TypeScript was designed to achieve some goals. TypeScript has two goals:

  • Provide an optional type system for JavaScript.
  • Provides an consistent, fully erasable, structural type system.

To achieve these goals consider following.

TypeScript Type System

Type systems improve your code by making it easier to read and by enforcing a certain degree of correctness at compile time.

Your JavaScript is TypeScript

TypeScript provides compiled version for JavaScript. The compiler is being able to check for obvious correctness problems. But the great thing is that the types are completely optional. Your JavaScript code .js file can be used as .ts file and TypeScript will results equivalent valid .js JavaScript file. TypeScript is a superset of JavaScript with optional Type checking.

Types can be Implicit

In TypeScript, type can be implicit and provide flexibility to improve productivity during code development. For example, in the following example TypeScript will know that Age is of type number. But it will give an error if you assign string value to it:

var Age = 23;
Age = '456'; // Error: cannot assign 'string' to 'number'

Types can be Explicit

In TypeScript, type can be explicit and allow programmers to accurately express the type that you are expecting and pre-validated by the TypeScript compiler. TypeScript uses postfix type annotations to specify type as it is popular in other optionally annotated languages.

var Age: number = 123;
var Age: number = '123'; // Error: cannot assign 'string' to 'number'

Types are Structural

In TypeScript, type can be structural and introduced through class and interface declarations and are referenced by the name given to them in their declarations. This means that duck typing is a first class language construct. Consider the following example.

TypeScript Example

interface CustomerA {
    Name: string;
    Address: string;
interface CustomerB {
    Name: string;
    Address: string;
    Phone: string;
var custA: CustomerA = { Name: "Jimi", Address: "12-13-288/A" }
var custB: CustomerB = { Name: "Jimi", Address: "12-13-288/A", Phone : "2344342111" }
function InsertCustomer(cust: CustomerA) { /* your code */ }

InsertCustomer(custA); // exact match okay
InsertCustomer(custB); // extra information okay
InsertCustomer({ Name: "Jimi" }); // Error: missing information 'Address'

Types can be Ambient

The major goal of TypeScript was to allow developers to use existing JavaScript library and slowly put effort in declarations so that you can get advantage of type safety + code intelligence. Let's consider a simple example of jquery. By default TypeScript expects you to declare before you use a variable.

$('.awesome').show(); // Error: cannot find name '$'

declare var $:any;
$('.awesome').show(); // Now okay!