Home > An Introduction to TypeScript
Sylvain Sidambarom
18 October 2018
Lire cet article en Français

An Introduction to TypeScript

introduction to typescript

Developing a web application nowadays is almost impossible without JavaScript. There is no doubt about the dominance of this language and its community is one of the largest in the web development world, probably on account of its built-in flexibility. TypeScript does have certain limitations, however, when it comes to developing complex applications. You guessed it, today’s post will be all about TypeScript.

We’ll start by looking at what TypeScript is and then what features this language provides compared to JavaScript. Next, we’ll go through the various key concepts and, finally, the various pros and cons.

 

What is TypeScript?

 

TypeScript is a programming language developed by Microsoft in 2012. Its main goal is to improve productivity when developing complex applications.

It is an open-source language developed as a JavaScript superset. This means that any code that is valid in JavaScript will also be valid in TypeScript.

The language introduces some optional functions as well, such as typing or object-oriented programming. No library is necessary to use these functions. Simply use the TypeScript compiler tool to transpile it (transform source code from one language into another language) into JavaScript. The executed code will be a JavaScript equivalent of the compiled TypeScript code.

 

How to Install and Configure TypeScript

 

There are two ways to install the tools needed for TypeScript:

 

If you have Visual Studio 2015 Update 3, Visual Studio 2017, or even Visual Studio Code, TypeScript is already installed by default. Here is the command to run to install TypeScript via npm:

npm install -g typescript

 

Below is a valid JavaScript code in a TypeScript file identified with the .ts extension.

function greeter(name) {
return "Bonjour, " + name;
}

let myName = "Sylvain Sidambarom";

document.body.innerHTML = greeter(myName);

 

To run this program, we need to compile it first using the following command:

tsc greeter.ts

 

This generates a greeter.js file in the same folder as the greeter.ts file.

function greeter(name) {

return "Bonjour, " + name;

}

var myName = "Sylvain Sidambarom";

document.body.innerHTML = greeter(myName);

 

Then, you just need to reference the JavaScript file in the HTML page to run the program.

<!DOCTYPE html>

<html>

<head><title>Mon premier programme Typescript</title></head>

<body>

<script src="greeter.js"></script>

</body>

</html>

 

 

Congratulations, you just created your first application in TypeScript! But what makes it different from a JavaScript application? Nothing at this point! And that is one of the benefits of TypeScript.

The fact that TypeScript is a JavaScript superset means it can easily be partially integrated into a project that is already in JavaScript.

In this next section, we’ll be using one of TypeScript’s key features, static typing.

 

TypeScript Basic Types

 

As you may already know, JavaScript is a strongly typed and dynamic language. The data type is not identified until runtime. This means that data types can change during runtime.

 

var test;

test = 1;

test = 'hello world';

test = function(a, b){

return a - b;

}

 

As the example above shows, throughout the program, the same variable can sometimes store a number, a character string, or even a function. This gives developers greater flexibility in how they develop their application. The downside of this flexibility, however, is that it can cause quite a few serious bugs if the data type is not properly controlled. After all, running the code is the only way of identifying the bugs.

TypeScript introduces slightly stronger typing than JavaScript. This typing is done through the addition of multiple basic types and static typing.

A language is said to use static typing when it checks variable types at compile time whereas a so-called dynamic typing language performs this check at runtime.

 

Type syntax

 

Typed variables are usually declared in TypeScript as follows:

let myVar: boolean;

let myVarinitialize: number = 2;

let bar = "hello world";

 

In the example below, the first two variable declarations are explicitly typed variables and the last one is implicitly typed. Remember that with some IDEs, you can also identify your data type by simply hovering over the variable storing the data. This feature is extremely useful in large projects as long as the types are explicitly declared.

 

Inferred typing

This is the method used by the TypeScript compiler to identify a variable type. When the compiler encounters the first occurrence of a variable, it tries to infer its type based on its use and then assumes that all other occurrences of that variable will have the same type.

 

Boolean

The most basic type. You can declare this type in two ways:

 

 

Number

TypeScript stores numbers as floating-point variables in the same way as JavaScript.

 

let anInt: number = 6;

let decimal: number = 2.9;

let hex: number = 0xa5d2;

 

Binary and octal data is also declared, the number type. This has been supported since ECMAScript 2015.

let binary: number = 0b1010;

let octal: number = 0o762;

 

String

In the same way as JavaScript again, the string variable type is declared as follows. You can also use single quotes, double quotes, and template strings with backticks (Alt+96).

 

In the following example, we are defining a greeter function that expects a string type parameter and returns a string type value.

 

If you try to use the greeter function with a number type parameter, you will see this error message during compilation.

greeter_string.ts:9:56 – error TS2345: Argument of type ‘number’ is not assignable to parameter of type ‘string’.

9 document.getElementById(“display”).innerHTML = greeter(thisYeah);

 

Note that this is often returned on the fly by IDEs that support TypeScript.

 

Introduction à Typescript

 

Array

Another subtlety in how JavaScript is replicated fully in TypeScript. The fact that this notion exists means you can declare an array of a specific type by adding brackets “[ ]” just after the type name. You can also use a generic write method, the Array generic type.

var names: string[] = [“Pierre”,”Paul”,”Jaques”];

var otherNames: Array<string> = [“Pierre”,”Paul”,”Jaques”];

 

Any

This type is unique. It is the type that is closest to JavaScript’s dynamic typing. You can assign any other data type to an any type variable.   This type is especially useful with third-party libraries when there is no declaration file and also for Ajax calls.

 

 

Void

Often used to declare the return type of a function that does not return a value. Although a void type variable is perfectly possible, I haven’t yet used this type.

function display(message: string): void{

console.log(message);

}

 

Enum

The enum type is quite a nice new feature. You can use it to make numerical data more legible and easier to understand. It avoids the need for magic numbers everywhere.

var myVar = 1;




if(myVar == 2)

console.log("L'eau bout");

 

Enum uses the same syntax as c#.

enum WaterState{

solid,

liquid,

gaz

}




var waterState: WaterState = WaterState.liquid;

 

The first enum value is 0 by default but you can specify the value for each enum element.

Hover the cursor over the enum value to see its actual numerical value.

 

Explicit Casting in TypeScript

 

With strongly typed languages, you sometimes need to explicitly specify an object type. Enter casting. There are two possible syntaxes available in TypeScript. The first involves adding any between “<” and “>” before the desired type variable.

var myObject = <any>{id:1, name:"John"};




myObject.id // id est du type “any” par le typage

// par déduction du compilateur

 

 

In the second, you add the keyword “as” followed by the desired type in front of the variable.

var myOtherObject = {id:2, name:”Peter”} as any;

 

Take care not to overuse casting to “any” as it can quickly lead to the problems associated with the JavaScript type mentioned earlier.

 

Functions in TypeScript

 

Functions in TypeScript are written in almost the same way as in JavaScript using types. Let’s go back to the greeter function from earlier.

 

function greeter(name) {

return "Bonjour, " + name;

}




let myName = "Sylvain Sidambarom";




document.body.innerHTML = greeter(myName);

 

A quick analysis of this function shows that it takes a string of characters as its parameter and it also returns a string of characters. You can incorporate these characteristics into the function signature as follows:

function greeter(name: string): string {

return "Bonjour, " + name;

}

 

If the function has optional parameters, simply add a question mark after the parameter name.

 

You can achieve the same result using initialized parameters, which gives the following:

 

TypeScript Interface

 

The interface provides a structure that allows you to define conditions (properties and/or methods) required for an object.

interface IPerson{

firstName: string;

lastName: string;

 

This interface is a simplified representation of a person. For an object to satisfy this interface, it must contain all of the properties and methods in this interface at a minimum.

The example below shows how to use this with the greeter method which only takes objects that implement the “IPerson” interface as parameters.

 

 

If the object does not implement the interface, the compiler indicates the missing elements. The “lastname” property is not defined here.

 

 

To use the “invalidPerson” variable anyway, you can define the variable or change the interface to make the “lastname” property optional by adding a question mark after the variable name, as shown below.

 

interface IPerson{

firstName: string;

lastName?: string;

}

 

Classes in TypeScript

 

The class is the notion that defines an object. It is one of the key concepts in object-oriented programming with interfaces. Interfaces are used in combination through structures called design patterns aimed at solving specific problems. Below is an example of class.

 

 

In this example, we defined a “Personnage” class. Use the keyword “this” to access class variables.

 

TypeScript Modules

 

A module is what .NET would refer to as an assembly or namespace. It is a logical grouping of classes and interfaces that can be used to structure a project and make it easier to make changes.

Use the keyword “module” to declare the module. Below is an example of how to declare and use a simple module.

 

 

In this example, the “greeting” method without parameters can be accessed through Module1 throughout the application whereas the “greeting” method with parameters can only be accessed in the file in which it is declared. Use the module as follows:

 

 

Module can declare classes as well as functions, constants, and interfaces.

 

Declaration Files

These are the files that contain the set of method signatures for a library. Among other things, they can be used to assist auto-completion and, in particular, to quickly access a library’s full API. This means you no longer need to know the library API inside out.

The main source for declaration files in this git repository: https://github.com/DefinitelyTyped/DefinitelyTyped. There, you will find a huge number of declaration files for known libraries. Bear in mind that these declaration files are updated by the community so there may be discrepancies between the library version and the declaration file version.

 

Introduction à Typescript

 

Here, we want to use lodash and the associated declaration file in the application we are installing with the commands above. Note the version difference between the library and the declaration file.

 

Introduction à Typescript

 

Introduction à Typescript

 

Installing the declaration file allows you to take advantage of auto-completion which is pretty useful when working with huge libraries. Try the following site to find the declaration file for a library: https://aka.ms/types

 

JavaScript Legacy Code to TypeScript Use Case

 

Similarly, you can start using TypeScript in a JavaScript project. Simply create TypeScript files in a separate folder and compile them in your deployment folder. If interactions between the files in TypeScript and JavaScript are necessary, consider using a specific type declaration file for the JavaScript code.

The simple example below shows a TypeScript code using a JavaScript legacy code.

 

TypeScript Legacy

 

 

  • legacy.js contains the legacy code.
  • App.ts contains the new TypeScript code.
  • Legacy-typing.d.ts contains the definition of the types in the set of elements to be used in the TypeScript.

 

 

The first line references the declaration file that contains the LegacyGreeter definition.

 

Declare a module in which you define a correction interface with the elements you want to use for the legacy code. Next, declare a global variable of the same type as the interface defined in the module.

 

The legacy code to be called at runtime is set out above.

This method means that the TypeScript can change without modifying the JavaScript, resulting in a more controlled migration from JavaScript to TypeScript.

 

Pros and Cons of Using TypeScript

 

Read on for the pros and cons of using TypeScript in a project.

 

TypeScript Pros

  • Typed language
  • Compilation in various ECMAScript versions from version 3 onward
  • Plenty of tools available
  • Object-oriented language with the introduction of typing, inheritance, and even notions of public and private
  • Gradual transition from JavaScript to TypeScript with the progressive introduction of types
  • Convert back easily with ECMAScript transpilation

 

TypeScript Cons

  • Executed code must be compiled in advance
  • Code has a more complicated syntax
  • Library declaration files are not always up to date
  • TypeScript does not correct JavaScript’s shortcomings, it limits some of their effects upstream

 

Save Time With TypeScript

 

TypeScript is a language that can cut development time by introducing object-oriented programming features. The compiler is a valuable tool for pinpointing errors fast as it shortens the time between writing the code and identifying any errors, mainly thanks to typing.

Note that transpiling TypeScript to JavaScript can reduce the barrier to using scripting languages for backend developers, delegates managing JavaScript’s subtleties to tools, and ensures control over cross-browser compatibility.

 

 

This posts should interest you
Hybrid workstation
The Hybrid Workstation
Today, as part of our hybridization content, we’re going to look at the hybrid workstation. The hybrid workstation uses technologies...
Comments
Leave a Reply

Your email address will not be published.

Receive the best of Cloud, DevOps and IT news.
Receive the best of Cloud, DevOps and IT news.