TypeScript Tutorial

In this tutorial, we will focus on sharing the most essential knowledge about TypeScript. We will learn what TypeScript is, how it works, and Types of data to keep in mind when learning TypeScript. 

What is TypeScript?

The TypeScript programming language is an open-source project by Microsoft. It is a strict superset of JavaScript and adds optional static type functionality to the language, developed by the father of C#, Anders Hejlsberg.

In the 2012s, he and his colleagues developed TypeScript so that associates could write large projects in Javascript. Overcoming the disadvantages of Javascript such as adding Interface, Type or Class in Javascript code. Turn Javascript from Free-typed to Static Typed during development.

The essence of TypeScript is to compile code written by programmers into Javascript. However, TypeScript will check the input and values ​​of the function just before it is compiled, so a lot of unexpected errors are avoided.

TypeScript uses all the features of ECMAScript 2015 (ES6) such as classes, modules.

How to use Typescript?

Before using Typescript, you need to install them. Two simple ways to install, they are:

  • Install Typescript through Node.js package manager (npm)
  • Install Typescript with the Visual Studio plugin.

Specifically, open Terminal, type the following command:

npm i -g typescript

And, you can program Typescript and compile them as .ts files and use the following command to translate:

tsc main.ts

When the operations are complete, you just need to open up the Visual Studio code and start playing with TypeScript.

Tutorial

TypeScript Variables

TypeScript adheres to the same way of setting variables as JavaScript. Variables can be declared using the keywords: var, let and const.

The var keyword in Typescript has the same functionality and scope as Javascript.

The let keyword was introduced in the latest version of JS (ES6). In the new version ES6 introduces 2 new keywords, let and const, to overcome the inadequacies in declaring variables with var.

Example of variable declaration with the let keyword:

let devName = "Tiffdoan";
// or
let devName:string = "Tiffdoan";

The let keyword is declared in the same way as var. But unlike the var keyword, when we declare let, its access scope is only within a block of code.

Let variables must be declared before use, and var can be used first and declared later.

Const variables are declared syntactically like let and var. The difference of const is that the value of the const variable is immutable, it is a constant.

In TypeScript we have 3 types of access modifiers: public, private and protected.

When a variable or method is declared public, it can be accessed anywhere.

class devName {
     public devCode: number;
     devName: string;
}

let dev = new devName();
dev.devCode = 100;
dev.devName = "Tiffdoan";

When a variable or method is declared private, it will be accessible only within that class and not from outside.

class devName {
     private devCode: number;
     devName: string;
}

let dev = new devName();
dev.devCode = 100; // Compiler Error
dev.devName = "Tiffdoan"; //OK

When a variable or method is declared protected, it will be accessed through parent and child inheritance. Learn more about TS variables in the article below:

TypeScript Arrays

Array in Typescript is an ordered list of data. It is similar to Array in Javascript. Arrays can contain elements of different data types.

Declare arrays

To declare an array of a specific element, you use the following syntax:

let arrayName: type[];

For example:

let webIT: Array<string>;
webIT = ['LearnShareIT', 'StackOverFlow'];

//Or use push() method:
webIT.push('LearnShareIT');

With the above example, the variable webIT is recognized by Typescript as a string data type.

Once you have defined an array with a specific data type, Typescript will prevent you from adding incompatible values to the array.

To be able to declare an array that can contain multiple data types, do as the following example:

let mynumber: (string | number)[] = ['one', 2, 'three', 5, 4];

Learn more about Arrays in our Array Typescript chapter.

Readonly keyword

In Typescript, readonly is used to make a property read-only. Read-only members can be accessed outside the class, array,.. but their value will not change.

For example:

const mydev: readonly string[] = ["TiffDoan"];
mydev.push("May"); // Error: Property 'push' does not exist on type 'readonly string[]'.

TypeScript Date

The date object in Typescript is where time matters are handled.

To initialize date object in javascript we have 4 ways:

  • Initialize the date and time at the current time: new Date();
  • Initialize date and time from time millisecond value: new Date(milliseconds);
  • Initialize date and time from a dateString: new Date(dateString);
  • Initialize date and time from a date string as attribute:

new Date(year, month, day, hours, minutes, seconds, milliseconds)

Specific examples:

let today = new Date();
// Wed Oct 12 2022 03:40:44 GMT+0700 (Indochina Time)

There are four basic formats of a date string: short date, long date, full date and ISO date.

Date in Typescript is like Javascript, it supports us with functions used to manipulate dates, including 2 types: Get date and Set date.

Some commonly used functions are:

  1. The support function to get common timestamps includes:
FunctionMeaning
getDate()The function returns the day of the month (from 1 – 31).
getDay()returns the day of the week (0-6), where Sunday is 0, Monday is 1, Tuesday is 2,…
getMonth()the function returns the month of the year (from 0 – 11), so we need to add 1.
getFullYear()returns the full five types of YYYY.
getHours()the function returns the number of hours in the form of 24h (from 0 – 23)
getMinutes()returns minutes in hours (0 – 59).
getSeconds() returns the number of seconds in minutes (0 – 59).
  1. The support function creates a timeline, including:
FunctionDescription
setDate()The function helps us to set the date (from 1 – 31).
setFullYear()function that helps us to set the full year in YYYY format.
setYear()The function helps us to set the last 2 digits of YY.
setHours()function helps us to set the number of hours (0 – 23)
setMonth()function that helps us to set the month (0 – 11)
setTime()The function helps us to set the time that has been converted to milliseconds.

TypeScript Elements

In this section, we will learn specifically about TypeScript elements when manipulating them with the DOM API. Typescript also supports you to manipulate HTML elements similar to Javascript.

Element is a base class built by objects contained in an HTML/XML document, for example: HTMLElement. You will need to pay attention to two commonly used interfaces, including Element and HTMLElement.

Retrieving document elements is one of the basic operations when using the DOM in programming with TypeScript.

The getElementById() method is one of the basic methods of the DOM, which retrieves specific elements of an HTML document and returns a reference to that element. The element must have an id attribute to be accessed using this method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>LearnShareIT: TypeScript Elements</title>
</head>
<body>
    <h1 id="welcome-heading">Welcome to LearnShareIT</h1>
    <script src="script.js">
        var x = document.getElementById('welcome-heading');
        console.log(x);
    </script>
</body>
</html>

At runtime, we can understand: using the variable x to contain the h1 element after using, document.getElementById(‘welcome-heading’) to access the element. Finally, use the console.log(x) method to check if the h1 element has been accessed.

When working with elements, you can also manipulate changes to the content, properties, and style of the element. Some specific methods below are applied:

Methodmeaning
element.innerHTML = new html contentChanges the inner content (content inside) of an HTML element
element.attribute = new valueChange an HTML element’s attribute with new value
element.setAttribute(attribute, value) Change an HTML element’s attribute
element.style.property = new styleChange an HTML element’s style

TypeScript Files

TypeScript is a superset of JavaScript. So any JavaScript file can be interpreted as a TypeScript file. A TypeScript file has the “.ts” extension, which is different from the Javascript “.js” extension.

To compile to a Typescript file, we use:

tsc <Filename>

Example: To compile the file “devLearnShareIT.ts”, we implement the syntax:

tsc devLearnShareIT.ts

And the output file will be devLearnShareIT.js

You can completely combine multiple Typescript files in one Javascript file. To do this, you will use the extra parameter outFile <OutputJSFileName>, for example: To compile 3 TypeScript files dev1.ts, dev2.ts, dev3.ts into one file “devLearnShareIT.js”, the syntax is:

tsc –outFile devLearnShareIT.js dev1.ts dev2.ts dev3.ts

In addition, you can also automatically generate a file ending in “.ts” on the real-time change of the file through the clock compiler.

TypeScript Maps

In Typescript you can completely use the same map function as Javascript. This is a data structure that allows you to store key-value pairs in the order of input.

Syntax to create a map:

let yourMap = new Map<string, number>();

If you want to add pairs of values to the map, we have:

let yourMap = new Map<string, string>([
         ["key1", "value1"],
         ["key2", "value2"]
     ]);

For example:

let devNameMapping = new Map<string>();

// Add entries
devNameMapping.set("ToanNguyen");
devNameMapping.set("HaiHoa");

In addition, you can also manipulate actions such as deleting, retrieving elements, and adding elements to the map.

FunctionMeaning
map.set(key, value)Adding key-value pairs to the map
map.get(key)Gets a value of a specified key in Map
map.has(key)Check if the key is in the map or not.
map.delete(key)Delete key-value pairs by specified key
map.clear()Delete all elements in the map
map.values()Function used to iterate over the specified values in the map.
map.entries()Function used to iterate over the specified entries in the map.

You can refer to more about how to implement the map in the articles below:

TypeScript Numbers

Numbers in Typescript are represented as floating-point values or large integers. Floating point numbers are of type number while large integers are of type big int.

Declaration syntax:

let price:number;

To initialize the value for price we have:

let price =8.15;

Numbers in Typescript is similar to Javascript Numbers, it also supports numeric characters for decimal, hexadecimal, binary, and octal literals.

TypeScript Objects

Typescript inherits the data types present  in Javascript. The data types in Typescript are divided into two types:

  • Primitive data types, including: string, number, boolean, null, symbol, undefined, ..
  • Object data types, including: functions, arrays, classes…

You can quickly distinguish between primitive and object data types by looking at the value. If the value itself has any properties, it is an object. Otherwise, it is one of eight primitive data types.

For example, you want to declare the object admin with its properties, we have:

let admin: {
     devName: string;
     career: string;
} = {
     devName: 'TiffDoan',
     career: 'Programmer'
};

In addition, you also need to pay attention and distinguish ‘object‘ and Object‘ in Typescript. object refers to non-primitive values, while Object describes the functions of objects.

TypeScript Strings

In Typescript, you would use single quotes ‘ or double quotes ” around literal characters to create strings.

For example:

let devName: string = 'TiffDoan';
let career: string = "Programmer";

Alternatively, you can also use the backtick (`). In addition to the same function as above, using this sign you can concatenate multiple strings together, for example:

let devName: string = `TiffDoan`;
let career: string = `Programmer`;
let intro: string = `I'm ${devName}.
I am a ${career}`;

console.log(intro);

Output:

I'm TiffDoan.
I am a Programmer.

You can learn more about TS String in the article Create And Work With TypeScript Strings

Summary

Thus, we have summarized the most necessary and basic knowledge about Typescript for you, especially for those who are just starting to learn about Typescript.

Basically, Typescript is similar to Javascript, so you can be confident that you will quickly grasp this language. To learn more about Typescript you can read articles related to it in LearnShareIT.

Other

Leave a Reply

Your email address will not be published. Required fields are marked *