AppDividend
Latest Code Tutorials

Typescript Tutorial Example | Beginners Guide To Typescript

4

Typescript Tutorial Example | Beginners Guide To Typescript is today’s topic. It is a typed superset of Javascript that compiles to plain JavaScript. TypeScript is an open-source object-oriented language maintained by Microsoft. Due to the static typing in TS, code written in TypeScript is more predictable and is generally easier to debug then normal JS. 

TypeScript has one extra compilation step to JavaScript that catches all kinds of errors before they reach runtime and break something in the code.

#What is TypeScript

Content Overview

TypeScript is a typed superset of JavaScript” but it assumes you know what a “superset” is and what “typed” means. Instead, to keep things simple you can think of TypeScript as of “a layer on top” of JavaScript.

TypeScript is a layer because you can write TypeScript code in your editor. After a compilation, all that TypeScript stuff is gone and you’re left with plain, simple JavaScript.

If the idea of the compilation step confuses you keep in mind that JavaScript is already compiled and then interpreted. There is a JavaScript engine that reads and executes your code.

JavaScript engines are not able to read TypeScript code so any TypeScript file should go under the “pre-translation” process, called compilation.

Only after the first compilation step, you’re left with pure JavaScript code, ready to run in the browser. You’ll see later how the TypeScript compilation is done.

For now, let’s keep in mind that TypeScript is a special kind of JavaScript but it needs a “translator” before running in a browser.

#What are types in TypeScript

By now you should’ve got a hint of what TypeScript does. Everything revolves around types. These are not the classic JavaScript “types” like String, Object, Boolean and so on.

TypeScript adds more type on its own like any (and more).

“any” in particular is a “loose” TypeScript type.

It means: this variable might be of any type: string, boolean, object, really, I don’t care. Which in fact is like having no type checking at all. With strict set to true instead you say to TypeScript “don’t allow ambiguity in my code”.

For this reason, I recommend keeping the max level of strictness on TypeScript, even if it can be harder to fix all errors at first. And now we’re almost ready to see TypeScript in action!

Typescript Tutorial Example For Beginners

Before we start coding, we need to install the TypeScript on our local machine. We can pull the typescript package using NPM, and it is better to install it globally by entering the following command.

npm install -g typescript

When it is installed, we can verify it by running the command.

tsc -v

It will display the version of typescript which is recently installed on your machine.

Typescript Tutorial Example For Beginners

#TypeScript coding example 

Let us write some code in typescript and see the output. The file extension for TypeScript is .ts.

Create one file called app.ts and add the following code.

// app.ts

const spiderman = (person) => {
    return 'Hello, ' + person;
}

let user = 'Peter Parker';
console.log(spiderman(user));

Now, first, we need to compile this code to Javascript, and then we can use that file in either server or browser. We will test our code on the server because we use Node.js.

Okay, now compile the file using the following command. It will generate the same-named javascript file.

tsc app.ts

So, in the project root, you can see that one more file has been created called app.js.

// app.js

var spiderman = function (person) {
    return 'Hello, ' + person;
};
var user = 'Peter Parker';
console.log(spiderman(user));

Now, run that file as a node server using the following command.

node app

It will return the output like below.

Typescript Tutorial Example | Beginners Guide To Typescript

#Text Editors With TypeScript Support

TypeScript is an open-source project but it is developed and maintained by Microsoft Inc. and it was initially supported only in Microsoft’s Visual Studio platform. Nowadays, there are lots of text editors and IDEs that either natively or through plugins have support for the TypeScript syntax, auto-complete suggestions, error catching, and even built-in 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.

#Static Typing | Type annotations

Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. Let’s see the following example.

// app.ts

const spiderman = (person: String) => {
    return 'Hello, ' + person;
}

let user = 1;
console.log(spiderman(user));

In the above example, we have told the TS compiler that spiderman function expects argument as a String and not an integer, object, or array datatype. Still, we have passed an integer argument. Now see the below output.

Type annotations in TypeScript

You can see that we have got an error saying that the number is not assignable to parameter String.

A compelling feature of TypeScript is the support of static typing. 

What it means that you can declare the types of variables, and the compiler will make sure that they are not assigned the wrong kinds of values.

#Datatypes In TypeScript

  1. Number – All the numeric values are represented by a number type, there aren’t separate definitions for integers, floats or others.
  2. String – The text type datatype, just like in vanilla JS strings can be surrounded by ‘single quotes’ or “double quotes.”
  3. Boolean – It is either true or false, using 0 and 1 will cause the compilation error.
  4. Any – A variable with this type can its value set to the string, number, or anything else.
  5. Arrays – Has two possible syntaxes: my_arr: number[] or my_arr: Array<number>.
  6. Void – Used on the function that doesn’t return anything.

#Object-oriented programming in TypeScript

TypeScript supports all the latest features of ES Next and object-oriented programmings, such as classes and interfaces.

This capability is a huge boost to JavaScript since it has always been struggling with its OOP functionality, especially since developers started using it for large scale applications.

#Interfaces in TypeScript

Interfaces are used to type-check whether the object has a specific structure or not. 

By defining an interface, we can name the particular combination of variables, making sure that they will always go together. 

When compiled from Typescript to JavaScript, interfaces disappear – their only purpose is to help in the development stage.

// app.ts

interface OS {
    name: String;
    language: String;
}
const desert = (type: OS): void => {
  console.log('Android ' + type.name + ' has ' + type.language + ' language');
};

const nougat = {
  name: 'N', 
  language: 'Java'
}

desert(nougat);

In the above example, we have created one interface called OS. It has two properties called name and language.

The next step is to define a function that has one argument called type, and it is the type of interface OS.

Now, you can compile that file to the JS and see the output.

tsc app.ts

Your app.js file looks like the below code.

// app.js

var desert = function (type) {
    console.log('Android ' + type.name + ' has ' + type.language + ' language');
};
var nougat = {
    name: 'N',
    language: 'Java'
};
desert(nougat);

The output is the following.

Interfaces in TypeScript

#Class in TypeScript

In an object-oriented programming language, the class is the template of objects. The class defines how an object would look like regarding that object’s functionalities.

The class also encapsulates the data for an object.

TypeScript has built-in support for classes, which were unsupported by ES5 and earlier versions of Javascript, what it means that we can use the class keyword to declare one easily.

Let’s see the following example.

// app.ts

class Car {
    model: String;
    doors: Number;
    isElectric: Boolean;
    
    constructor(model: String, doors: Number, isElectric: Boolean) {
        this.model = model;
        this.doors = doors;
        this.isElectric = isElectric;
    }

    make(): void {
        console.log(`This car is ${this.model} which has ${this.doors} doors` );
    }
}
let newCar = new Car('Innova', 4, false);
newCar.make();

In the above example, we have defined one class, which has a parameterized constructor, properties, and methods.

Then we have created an object of that class and passed the parameter to construct an object and assign the values.

Then we have called the make method to create and show the car in the console. Compile the file and see the output inside the console.

tsc app.ts

If the code is errorless then, you will see the updated app.js file and now run that file.

node app

See the output below.

Class in TypeScript

Finally, Typescript Tutorial Example | Beginners Guide To Typescript is over.

Recommended Posts

How to setup typescript with webpack 4

Beginner’s Guide To Setup TypeScript With Webpack

How to use TypeScript with Vue js

4 Comments
  1. Foon Lam says

    Krunal,
    The line :-
    console.log(‘This car is ${this.model} which has ${this.doors} doors’);
    only prints :-
    This car is ${this.model} which has ${this.doors} doors
    I had to remove the “$” sign and the curly braces and change it to this :-
    console.log(‘This car is ‘ + this.model + ‘ which has ‘ + this.doors + ‘ doors’);
    before it was able to print :-
    This car is Innova which has 4 doors

    1. Jacob says

      that was because you use ” instead of “this is a string template that is in ES6 so if you used ‘ ‘ you needed to delete the {} and $, and add the +.

    2. Vicky Singh says

      you have to use bacticks(“) and then use $ in it

  2. Johan says

    @Foon Lam Says
    You are using single-qoutes, that’s why it’s not working.
    Use have to use ‘backticks’ instead.
    https://stackoverflow.com/questions/27678052/usage-of-the-backtick-character-in-javascript

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.