• Whizzystack Solutions

Learning Typescript In 30 Minutes

Updated: Jun 28





Today we're getting to take a glance at matter, a compile-to-JavaScript language designed for developers to build massive and sophisticated apps. It inherits several programming ideas from languages like C# and Java that add a lot of discipline and order to the otherwise terribly relaxed and free-typed JavaScript.

This tutorial is aimed toward those who are fairly skilful in JavaScript however still beginners are once it involves matter. We've lived most of the fundamentals and key options whereas together with voluminous examples with commented code to assist you see the language in action. Let's begin!


Benefits of Using Typescript



JavaScript is pretty smart because it is and you'll surprise Do I actually ought to learn Typescript? Technically, you are doing not ought to learn matter to be a decent developer, the general public do exactly fine while not it. However, operating with matter undoubtedly has its benefits: Due to the static writing, code written in matter is a lot of sure, and is usually easier to right.


Makes it easier to arrange the code base for terribly massive and complex apps because of modules, namespaces and robust OOP support. Typescript contains a compilation step to JavaScript that catches every kind of errors before they reach runtime and break one thing. The approaching Angular two frameworks is written in matter and it's counseled that developers use the language in their daily use also.


The last purpose is really the foremost necessary to several individuals and is that the main reason to induce them into matter. Angular two is one amongst the most popular frameworks right away and though developers will use regular JavaScript with it, a majority of the tutorials and examples square measure written in TS. As Angular two expands its community, it's natural that a lot of and a lot of individuals are going to be learning matter.


Recent rise of Typescript’s popularity, data from Google Trends.

Installation


Installing TypeScript




You will need Node.js and Npm for this tutorial. Go here if you don't have them installed.

The easiest way to setup Typescript is via npm. Using the command below ,we can install the Typescript package globally, making the TS compiler available in all of our projects:

 npm install -g typescript
 

Try opening a terminal anywhere and running tsc -v to see if it has been properly installed.

tsc -v
Version 1.8.10

Text editors


Text Editors with TypeScript Support


TypeScript is an open-source project however is developed and maintained by Microsoft and intrinsically was originally supported solely in Microsoft's Visual Studio platform. Nowadays, there are heaps additional text editors and day that either natively or through plugins provide support for the matter syntax, auto-complete suggestions, error catching, and even integral compilers.

1. Visual Studio Code - Microsoft's other, lightweight open-source code editor. TypeScript support is built in.

2. Official Free Plugin for Sublime Text.

3. The latest version of WebStorm comes with built in support.

4. More including Vim, Atom, Emacs and others

Compilation


Compiling to JavaScript


TypeScript is written in .ts files (or .tsx for JSX), that cannot be used directly within the browser and want to be translated to vanilla .js first. This compilation method is often worn out variety of various ways:

· In the terminal using the previously mentioned command line tool tsc.

· Directly in Visual Studio or some of the other IDEs and text editors.

· Using automated task runners such as gulp.


We found the first way to be easiest and most beginner friendly, so that's what we're going to use in our lesson.

The following command takes a TypeScript file named main.ts and translates it into its JavaScript version main.js. If main.js already exists it will be overwritten.

 
tsc main.ts

We can also compile multiple files at once by listing all of them or by applying wildcards:

# Will result in separate .js files: main.js worker.js.
tsc main.ts worker.ts 
 
# Compiles all .ts files in the current folder. Does NOT work recursively.
tsc *.ts

We can also use the --watch option to automatically compile a TypeScript file when changes are made:

# Initializes a watcher process that will keep main.js up to date.
tsc main.ts --watch

More advanced TypeScript matter users may produce a tsconfig.json file, consisting of varied build settings. A configuration file is incredibly handy once acting on massive comes with variant .ts files since it somewhat automates the method. You’ll be able to browse additional concerning tsconfig.json within the matter docs here

Static typing


Static Typing


A very delicacy of matter is that the support of static writing. This suggests that you simply will declare the categories of variables, and therefore the compiler can make certain that they don't seem to be assigned the incorrect kinds of values. If kind declarations are omitted, they're going to be inferred mechanically from your code.

Here is an example. Any variable, operate argument or come price will have its kind outlined on initialization:

var burger: string = 'hamburger', // String 
 calories: number = 300, // Numeric
 tasty: boolean = true; // Boolean
 
// Alternatively, you can omit the type declaration:
// var burger = 'hamburger';
 
// The function expects a string and an integer.
// It doesn't return anything so the type of the function itself is void.
 
function speak(food: string, energy: number): void {
 console.log("Our " + food + " has " + energy + " calories.");
}
 
speak(burger, calories);

Because TypeScript is compiled to JavaScript, and the latter has no idea what types are, they are completely removed:

 
// JavaScript code from the above TS example.
 
var burger = 'hamburger',
 calories = 300, 
 tasty = true; 
 
function speak(food, energy) {
 console.log("Our " + food + " has " + energy + " calories.");
}
 
speak(burger, calories);

However, if we try to do something illegal, on compilation tsc will warn us that there is an error in our code. For example:

// The given type is boolean, the provided value is a string.
var tasty: boolean = "I haven't tried it yet";
 
 
main.ts(1,5): error TS2322: Type 'string' is not assignable to type 'boolean'.
 

It will also warn us if we pass the wrong argument to a function:

function speak(food: string, energy: number): void{
 console.log("Our " + food + " has " + energy + " calories.");
}
 
// Arguments don't match the function parameters.
speak("tripple cheesburger", "a ton of");
 
 
main.ts(5,30): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Here are some of the most commonly used data types:


· Number - All numeric values are represented by the number type, there aren't separate definitions for integers, floats or others.

· String - The text type, just like in vanilla JS strings can be surrounded by 'single quotes' or "double quotes".

· Boolean - true or false, using 0 and 1 will cause a compilation error.

· Any - A variable with this type can have it's value set to a string, number, or anything else.

· Arrays - Has two possible syntaxes: my_arr: number[]; or my_arr: Array<number>.

· Void - Used on function that don't return anything.

To see a list of all of the available types, go to the official TypeScript docs - here.



Interfaces


Interfaces


// Here we define our Food interface, its properties, and their types.
interface Food {
 name: string;
 calories: number;
}
 
// We tell our function to expect an object that fulfills the Food interface. 
// This way we know that the properties we need will always be available.
function speak(food: Food): void{
 console.log("Our " + food.name + " has " + food.calories + " calories.");
}
 
// We define an object that has all of the properties the Food interface expects.
// Notice that types will be inferred automatically.
var ice_cream = {
 name: "ice cream", 
 calories: 200
}
 
speak(ice_cream);

The order of the properties does NOT matter. We just need the required properties to be present and to be the right type. If something is missing, has the wrong type, or is named differently, the compiler will warn us.

interface Food {
 name: string;
 calories: number;
}
 
function speak(food: Food): void{
 console.log("Our " + food.name + " has " + food.calories + " grams.");
}
 
// We've made a deliberate mistake and name is misspelled as nmae.
var ice_cream = {
 nmae: "ice cream", 
 calories: 200
}
 
speak(ice_cream);
 
 
 
 
 
 
main.ts(16,7): error TS2345: Argument of type '{ nmae: string; calories: number; } 
is not assignable to parameter of type 'Food'. 
Property 'name' is missing in type '{ nmae: string; calories: number; }'.


This is a beginner’s guide so we won't be going into more detail about interfaces. However, there is a lot more to them than what we've mentioned here so we recommend you check out the TypeScript docs - here.


Classes and loop


Classes


When building giant scale apps, the article orientated type of programming is most popular by several developers, most notably in languages like Java or C#.

Matter offers a category system that's terribly the same as the one in these languages, together with inheritance, abstract categories, interface implementations, setters/getters, and more. It's also truthful to say that since the foremost recent JavaScript update (ECMAScript 2015), categories are native to vanilla JS and may be used while not matter. The 2 implementation are terribly similar however have their variations, matter being a touch a lot of strict. Continuing with the food theme, here could be a easy matter class:

class Menu {
 // Our properties:
 // By default they are public, but can also be private or protected.
 items: Array<string>; // The items in the menu, an array of strings.
 pages: number; // How many pages will the menu be, a number.
 
 // A straightforward constructor. 
 constructor(item_list: Array<string>, total_pages: number) {
 // The this keyword is mandatory.
 this.items = item_list; 
 this.pages = total_pages;
 }
 
 // Methods
 list(): void {
 console.log("Our menu for today:");
 for(var i=0; i<this.items.length; i++) {
 console.log(this.items[i]);
 }
 }
 
} 
 
// Create a new instance of the Menu class.
var sundayMenu = new Menu(["pancakes","waffles","orange juice"], 1);
 
// Call the list method.
sundayMenu.list();

Anyone who has written at least a bit of Java or C# should find this syntax comfortably familiar. The same goes for inheritance:

class HappyMeal extends Menu {
 // Properties are inherited
 
 // A new constructor has to be defined.
 constructor(item_list: Array<string>, total_pages: number) {
 // In this case we want the exact same constructor as the parent class (Menu), 
 // To automatically copy it we can call super() - a reference to the parent's constructor.
 super(item_list, total_pages);
 }
 
 // Just like the properties, methods are inherited from the parent.
 // However, we want to override the list() function so we redefine it.
 list(): void{
 console.log("Our special menu for children:");
 for(var i=0; i<this.items.length; i++) {
 console.log(this.items[i]);
 }
 
 }
}
 
// Create a new instance of the HappyMeal class.
var menu_for_children = new HappyMeal(["candy","drink","toy"], 1);
 
// This time the log message will begin with the special introduction.
menu_for_children.list();

For a more in-depth look at classes in TS you can read the documentation - here.


Generics


Generics


Generics area unit templates that enable an equivalent operate to simply accept arguments of varied differing kinds. Making reusable elements victimization generics is healthier than victimization the any information sort, as generics preserve the categories of the variables that go into and out of them.

A quick example would be a script that receives an argument and returns an array containing that same argument.

// The <T> after the function name symbolizes that it's a generic function.
// When we call the function, every instance of T will be replaced with the actual provided type.
 
// Receives one argument of type T,
// Returns an array of type T.
 
function genericFunc<T>(argument: T): T[] { 
 var arrayOfT: T[] = []; // Create empty array of type T.
 arrayOfT.push(argument); // Push, now arrayOfT = [argument].
 return arrayOfT;
}
 
var arrayFromString = genericFunc<string>("beep");
console.log(arrayFromString[0]); // "beep"
console.log(typeof arrayFromString[0]) // String
 
var arrayFromNumber = genericFunc(42);
console.log(arrayFromNumber[0]); // 42
console.log(typeof arrayFromNumber[0]) // number

The first time we have a tendency to known as the perform we have a tendency to manually set the kind to string. This is not needed because the compiler will see what argument has been passed and mechanically decide what kind suits it best, like within the second decision. Though it is not obligatory, providing the kind when is taken into account sensible follow because the compiler may fail to guess the proper type in additional complicated situations.

The TypeScript docs include a couple of advanced examples including generics classes, combining them with interfaces, and more. You can find them here.


Modules


Modules


Another necessary thought once engaged on giant apps is modularity. Having your code split into several little reusable parts helps your project keep organized and perceivable, compared to having one 10000-line file for everything.

TypeScript introduces a syntax for commercialism and mercantilism modules, however cannot handle the particular wiring between files. To change external modules TS depends on third-party libraries: need.js for browser apps and CommonJS for Node.js. Let's take a glance at a straightforward example of matter modules with need.js:

We will have two files. One exports a function, the other imports and calls it.


exporter.ts

var sayHi = function(): void {
 console.log("Hello!");
}
 
export = sayHi;

importer.ts

import sayHi = require('./exporter');
sayHi();

Now we need to download require.js and include it in a script tag - see how here. The last step is to compile our two .ts files. An extra parameter needs to be added to tell TypeScript that we are building modules for require.js (also referred to as AMD), as opposed to CommonJS ones.

tsc --module amd *.ts

Modules are quite complex and are out of the scope of this tutorial. If you want to continue reading about them head out to the TS docs - here.

Declaration files


Third-party Declaration Files


When employing a library that was originally designed for normal JavaScript, we'd like to use a declaration file to create that library compatible with matter. A declaration file has the extension .d.ts and contains varied data regarding the library and its API.

TypeScript declaration files are sometimes written by hand, however there is a high probability that the library you wish already includes a .d.ts. file created by someone else. DefinitelyTyped is that the biggest public repository, containing files for over cardinal libraries. there's additionally a preferred Node.js module for managing matter definitions referred to as Typings.

If you still need to write a declaration file yourself, this guide will get you started.

Typescript 2.0 features.


Upcoming Features in TypeScript 2.0


TypeScript is still under active development and is evlolving constantly. At the time of the writing of this tutorial the LTS version is 1.8.10, but Microsoft have already released a Beta for TypeScript 2.0. It's available for public testing and you can try it out now:


npm install -g typescript@beta

It introduces some handy new concepts such as:


· Non-nullable types flag which prevents some variables from having their value set to null or undefined.

· New improved system for getting declaration files directly with an npm install.

· Control flow type analysis that catches errors previously missed by the compiler.

· Some innovations in the module export/import syntax.


Another long-awaited feature is the ability to control the flow of asynchronous functions in an async/await block. This should be available in a future 2.1 update.


Conclusion

We hope you enjoyed this tutorial! Do you have any thoughts on matter and would you concentrate on victimization it in your projects? Be happy to depart a comment below!


We will be happy to answer your questions on designing, developing, and deploying comprehensive enterprise web, mobile apps and customized software solutions that best fit your organization needs.

As a reputed Software Solutions Developer we have expertise in providing dedicated

remote and outsourced technical resources for software services at very nominal cost. Besides experts in full stacks We also build web solutions, mobile apps and work on system integration, performance enhancement, cloud migrations and big data analytics. Don’t hesitate to get in touch with us!

31 views

Recent Posts

See All
whizzystack logo

About Us

 

We build & support your own talented, trusted, full-time development team hosted out of Whizzystack’s headquarters in India. We also deliver world class product and software development services Read more

Whizzystack

Our Developers

Contact Us

 New Jersey     

+1(877)3685420

 sid.baker@whizzystack.com 

 

 India   

+91(95)60641297

 +91(120)4287309 

 info@whizzystack.com

Subscribe to Our Blog

Sign up to receive email notifications when Whizzystack drops more knowledge.

  • LinkedIn
  • Facebook
  • Twitter
  • Instagram
  • RSS