/react-typescript

react-typescript

Primary LanguageTypeScript

react-typescript

Defining TypeScript

TypeScript is an object-oriented programming language developed and maintained by the Microsoft Corporation. It is a superset of JavaScript and contains all of its elements.

TypeScript totally follows the OOPS concept and with the help of TSC (TypeScript Compiler), we can convert Typescript code (.ts file) to JavaScript (.js file)

Typescript is a superset of JavaScript.

A Brief History of TypeScript

In 2010, Anders Hejlsberg (the creator of TypeScript) started working on TypeScript at Microsoft and in 2012 the first version of TypeScript was released to the public (TypeScript 0.8). Although the release of TypeScript was praised by many people around the world, due to the lack of support by major IDEs, it was not majorly adopted by the JavaScript community.

The First Version of TypeScript (TypeScript 0.8) Released to the Public October 2012.

The latest version of Typescript (Typescript 3.0) was released to the public in July 2018 and you can
download the latest version here!

Why Should We Use TypeScript?

  • TypeScript simplifies JavaScript code, making it easier to read and debug.
  • TypeScript is open source.
  • TypeScript provides highly productive development tools for JavaScript IDEs and practices, like static checking.
  • TypeScript makes code easier to read and understand.
  • With TypeScript, we can make a huge improvement over plain JavaScript.
  • TypeScript gives us all the benefits of ES6 (ECMAScript 6), plus more productivity.
  • TypeScript can help us to avoid painful bugs that developers commonly run into when writing JavaScript by type checking the code.
  • Powerful type system, including generics.
  • TypeScript is nothing but JavaScript with some additional features.
  • Structural, rather than nominal.
  • TypeScript code can be compiled as per ES5 and ES6 standards to support the latest browser.
  • Aligned with ECMAScript for compatibility.
  • Starts and ends with JavaScript.
  • Supports static typing.
  • TypeScript will save developers time.
  • TypeScript is a superset of ES3, ES5, and ES6.

Additional Features of TypeScript

  • Functions with optional parameters.
  • Functions with REST parameters.
  • Generics support.
  • Modules support.

What Others Said About TypeScript:

  • “We love TypeScript for many things… With TypeScript, several of our team members have said things like ‘I now actually understand most of our own code!’ because they can easily traverse it and understand relationships much better. And we’ve found several bugs via TypeScript’s checks.” — Brad Green, Engineering Director – Angular

  • “One of Ionic’s main goals is to make app development as quick and easy as possible, and the tooling support TypeScript gives us with autocompletion, type checking and source documentation really aligns with that.” — Tim Lancina, Tooling Developer – Ionic

  • “TypeScript is a smart choice when writing a modern web- or JavaScript-based application. TypeScript’s carefully considered language features and functionality, and its consistently improving tools result in a terrifically productive development experience.” — Aaron Cornelius, Research Fellow – Epic

  • “TypeScript helped us to reuse the team’s knowledge and to keep the same team velocity by providing the same excellent developer experience as C#… A huge improvement over plain JavaScript.” — Valio Stoychev, PM Lead – NativeScript

Top TypeScript Features You Might Not Know

Object-Oriented Programming

TypeScript includes a very good set of Object Oriented Programming (OOP) features, that are good to maintain robust and clean code; this improves the code quality and maintainability. These OOP features make TypeScript code very clean and organized.

Example:

class CustomerModel
{
    customerId:  number;
    companyName: string;
    contactName: string;
    country: string;
}
class CustomerOperation{
    addCustomer(customerData: CustomerModel) : number {
    //add customer
    let customerId =5;// Id returned after save
     return customerId;
}
}

Interfaces, Generics, Inheritance, and Method Access Modifiers

TypeScript supports interfaces, generics, inheritance, and method access modifiers. Interfaces are a good way of specifying a contract. Generics help to provide compile-time checking, inheritance enables new objects to take on the properties of existing objects, and access modifiers control the accessibility of the members of a class. TypeScript has two access modifiers — public and private. By default, the members are public but you can explicitly add a public or private modifier to them.

Interface:

interface ITax {
    taxpayerId: string;
    calculateTax(): number;
    }
class IncomeTax implements ITax {
    taxpayerId: string;
    calculateTax(): number {
    return 10000;
    }
}
class ServiceTax implements ITax {
    taxpayerId: string;
    calculateTax(): number {
    return 2000;
    }
}

Access Modifiers and Properties:

class Customers{
    public companyname:string;
    private country:string;
}

Showing one public and one private variable.

Inheritance:

class Employee{
    Firstname:string;
    }
class Company extends Employee {
    Department:string;
    Role:string
    private AddEmployee(){
    this.Department="myDept";
    this.Role="Manager";
    this.FirstName="Test";
    // do the operation
    }
}

Generics:

function identity<T> (arg: T): T {
    return arg; 
    }
    //example showing implementation of generics
    let output = identity <string>("myString");
    let outputl = identity <number> (23);

Strongly/Static Type

TypeScript does not allow intermixing of values with different datatypes. When such restrictions are violated, errors are thrown. Therefore, you have to define types when declaring variables and you cannot assign other values other than the type defined which is very possible in JavaScript.

Example:

let testnumber:  number = 6;
testnumber = "myNumber"; // This will throw an error.
testnumber = 5; // This will work


Compile-Time/Static Type Checking

If we do not follow the proper syntax and semantics of any programming language, then compile-time errors are thrown by the compiler. They will not let your program to execute a single line until you remove all the syntax errors or until you debug the compile time errors. It is the same case with TypeScript as well.

Example:

let isDone: boolean = false;
isDone = "345";  //This will throw an error.
isDone = true; //This will work

Less Code Compared to JavaScript

TypeScript is a wrapper around JavaScript so helper classes are available that reduces the code. Code in Typescript is easier to understand.

Readability

Interfaces, classes, etc. provide readability to the code. As the code is written in classes and interfaces, it is more meaningful and easy to read and understand.

Example:

class Greeter {
    private greeting: string;
    constructor (private message: string) {
    this.greeting = message;
    }
    greet() {
    return "Hello, " + this.greeting;
    }
}

JavaScript code:

var Greeter = (function () {
    function Greeter(message) {
    this.greeting = message;
    }
    Greeter.prototype.greet = function () {
    return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Compatibility

Typescript is compatible with JavaScript libraries like underscore.js, Lodash, etc. They have many built-in and easy to use functions that make development faster.

Provide a “Compiler” That Can Convert Code to JavaScript-Equivalent Code

TypeScript code consists of plain JavaScript code as well as certain keywords and constructs specific to TypeScript. However, when you compile the TypeScript code it is converted into plain JavaScript. That means the resultant JavaScript can be used with any browser that supports JavaScript.

Supports Modules

As your TypeScript code base grows, it becomes important to organize classes and interfaces for better maintainability. TypeScript modules allow you to do just that. A module is a container for your code that helps you organize your code in a neat way. Conceptually, you may find them similar to .NET namespaces.

Example:

module Company {
    class Employee {
    }
    class EmployeeHelper {
    targetEmployee: Employee;
    }
    export class Customer {
    }
}
var obj = new Company.Customer();

ES6 Feature Support

Typescript is a superset of ES6, so all feature of ES6 are there plus some additional features like it supports Arrow Function commonly called lambda function. ES6 has introduced a slightly different syntax to define anonymous functions called the fat arrow syntax.

Example:

setTimeout(() => {
console.log("setTimeout called!")
}, 1000);

Used in Popular Frameworks

TypeScript has become more and more popular over the last few years. Maybe the defining moment of TypeScript popularity was the time when Angular 2 officially switched to TypeScript, which was a win-win situation.

Reduces Bugs

It reduces bugs like null handling, undefined, etc. Strongly typed characteristics restrict developers to write type-specific code with proper checks.

Function Overloading

TypeScript allows you to define overloaded functions. This way you can invoke different implementations of a function depending on the parameter. Remember, however, that TypeScript function overloading is a bit odd and requires type checking during the implementation. This limitation is due to the fact that TypeScript code finally gets compiled into plain JavaScript and JavaScript doesn’t support the concept of function overloading in its true sense.

Example:

class functionOverloading{
    addCustomer(custId: number);
    addCustomer(company: string);
    addCustomer(value: any) {
        if (value && typeof value == "number") {
        alert("First overload - " + value);
        }
        if (value && typeof value == "string") {
        alert("Second overload - " + value);
        }
    }
}

Constructors

The classes you define in TypeScript can have a constructor. The constructor usually does the job of initializing the object by setting default values to its properties. The constructor can also be overloaded just like a function.

Example:

export class SampleClass{
    private title: string; 
    constructor(public constructorexample: string){
    this.title = constructorexample; 
    }
}

Debugging

It is easy to debug the code written with TypeScript.

TypeScript Is Just JavaScript

TypeScript starts with JavaScript and ends with JavaScript. Typescript adopts the basic building blocks of your program from JavaScript. All TypeScript code is converted into its JavaScript equivalent for the purpose of execution.

Example:

class Greeter {
    greeting: string;
    constructor (message: string) {
    this.greeting = message;
    }
    greet() {
    return "Hello, " + this.greeting;
    }
}

JavaScript code:

var Greeter = (function () {
    function Greeter(message) {
    this.greeting = message;
    }
    Greeter.prototype.greet = function () {
    return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Portable

TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on. Unlike its counterparts, TypeScript does not need a dedicated VM or a specific runtime environment to execute.

Source dzone.com/