What is a .ts File? Typescript Beginner Tutorial

What is a .ts File? Typescript Beginner Tutorial

.ts is the file extension for Typescript files. In today’s article, we will learn about the basics of Typescript.

Typescript has been the hype for the past couple of months. Even Bill Gates, the founder of Microsoft, has been talking about it.

Bill Gates talking about Typescript

Here is the chart showing Typescript’s popularity:

Chart showing Typescrpt’s popularity

And in terms of awareness, interest, and satisfaction, Typescript is the most popular programming language in the world.

Awareness, interest, and satisfaction rankings

What is Typescript?

Typescript is a superset of Javascript.

  • It is a programming language that compiles to Javascript and is developed.
  • It is maintained by Microsoft.
  • It is open source and free to use.

Link to the TypeScript Source Code: microsoft/TypeScript

Features of Typescript

Javascript as you might already know is a loosely typed language. This means that you can do things like this:

let a = 10;
a = "hello";Code language: JavaScript (javascript)

Here the value of a was initially a number, but later you assigned a string to it.

Whereas, Typescript is a strongly typed language i.e it has static-checking capabilities.

The biggest benefit of static-checking is the tooling that we can get in our IDEs like VSCode. With the help of static-checking, we can get:

  • autocomplete suggestions
  • type checking, and
  • compilers can catch bugs in advance, this makes development a lot easier

Here is what the previous example would look like in Typescript:

Clearly, we can see it detects that the variable a was declared as a number and we are trying to assign a string to it. This is a very basic example but this kind of type check can be very helpful in large projects.

This is why Typescript is so popular and is getting wide adoption.

What are the prerequisites to learn Typescript?

Since Typescript is a superset of Javascript, any JS code is a valid TS code as well. And TS also guarantees that the code will be supported in any environment even if we use future features of JS. This is because we can transpile TS code to any flavor of JS code.

How to use Typescript?

In your local machine

You need to have node installed on your machine. You can download it from here.

Then you can install Typescript using the following command:

npm install -g typescript

This will install Typescript globally on our system. You can check the version of Typescript by running the following command:

tsc --version

NOTE: tsc stands for “Typescript Compiler”.

In Codedamn Playgrounds

You can learn Typescript in Codedamn Playgrounds as well. It is a free online IDE for learning web development. It has the tsc command pre-installed.

Follow the steps to set up your Typescript project in Codedamn Playgrounds:

  1. Go to Codedamn Playgrounds.
  2. Select the very first playground template “HTML/CSS” and click on “Create Playground” on the pop-up.
  1. It should open an IDE in your browser.
  1. Create a new file by clicking on the “New File” button. And name it script.ts.
  1. Click on the “Split Terminal” button and type the following command:
tsc script.ts --watchCode language: CSS (css)

This will watch for any changes in the script.ts file and transpile it to script.js file every time you save the file.

  1. Type the following code in the script.ts file:
console.log("Hello World");Code language: TypeScript (typescript)

You will notice that the contents of script.js file will be updated automatically. Now, if you click on the “Toggle Browser Logs” button at the bottom right, it will open the console and you will see the output.

Your Typescript playground is ready. You can now start learning Typescript.

Typescript Configuration

By default, Typescript will transpile the code to ES3. ES3 didn’t have support for async/await. So, let’s see what happens when we use async/await in Typescript.

Add the following code to the script.ts file:

async function hello() {
  console.log("Hello World");
}Code language: TypeScript (typescript)

Once, tsc compiles this file, open the script.js file and you will see that there is a lot of generator code. But we can change this behavior by creating a tsconfig.json file. This file will contain the configuration for Typescript.

Create a new file named tsconfig.json and add the following code:

{
  "compilerOptions": {
    "target": "es2017",
    "watch": true
  }
}Code language: JSON / JSON with Comments (json)

Stop the current tsc process by Ctrl+C and run the following command:

tsc

Now, open the script.js file and you will see that the code is much cleaner.

NOTE: This time we are not using the --watch flag with tsc. This is because we have already added the watch option in the tsconfig.json file.

You can learn more about the tsconfig.json file here.

Defining Types

Type inference is the process of inferring the type of a variable from its value. In Typescript, we don’t have to explicitly declare the type of a variable. Typescript can infer the type of the variable from its value. For example:

let a = 10;Code language: TypeScript (typescript)

We can also explicitly define the type of a variable. For example:

let a: number = 10;
Code language: TypeScript (typescript)

Please note the syntax of the above code. We have added a colon : after the variable name and then the type of the variable. This is called a type annotation.

If we now try to assign a string to the variable a, we will get an error.

a = "hello"; // will give an error saying "Type 'string' is not assignable to type 'number'"
Code language: TypeScript (typescript)

We can also define the types of parameters and the return type of a function. For example:

function add(a: number, b: number): number {
  return a + b;
}
Code language: TypeScript (typescript)

Here, a and b are the parameters of the function. We have defined their types as number. The return type of the function is also number. So, if we call this function with strings, we will get an error. Also, the return value has to be assigned to a variable declared as a number.

add("hello", "world"); // will give an error saying "Argument of type '"hello"' is not assignable to parameter of type 'number'"
let res:string = add(1, 2); // will give an error saying "Type 'number' is not assignable to type 'string'"
Code language: TypeScript (typescript)

But,

let res: number = add(1, 2); // will work
Code language: TypeScript (typescript)

Types in Typescript

Let’s take a look at all types that Typescript supports:

Primitive Types

Primitive types are the basic types in Typescript. They are:

  • number
  • string
  • boolean
Number

This is used to represent numbers like 123. For example:

let cgpa: number = 10;
Code language: TypeScript (typescript)

NOTE: Typescript doesn’t have a separate type for integers. It only has a single type called number which can be used to represent both integers and floating point numbers.

String

This is used to represent strings. For example:

let message: string = "hello";
Code language: TypeScript (typescript)
Boolean

This is used to represent boolean values (true or false). For example:

let isSet: boolean = true;
Code language: TypeScript (typescript)

Non-Primitive Types

Array

Array refers to a collection of items. For example:

let scores: number[] = [1, 2, 3];
Code language: TypeScript (typescript)

Here, scores is an array of numbers only. If we try to add a string to the array, we will get an error.

scores.push("hello"); // will give an error saying "Argument of type '"hello"' is not assignable to parameter of type 'number'"
Code language: TypeScript (typescript)
Tuple

This is used to represent arrays with a fixed number of elements. For example:

let todo: [number, string] = [1, "water the plants"]

// CORRECT
todo[0] = 2 // Since, first item is number we can assign number
todo[1] = "groceries"


// WRONG
todo[0] = "test" // Type 'string' is not assignable to type 'number'
todo[1] = 2      // Type 'number' is not assignable to type 'string'.
Code language: TypeScript (typescript)
Enum

This is used to represent a set of named constants. For example:

enum Color {
  Red,
  Green,
  Blue
}

let houseColor: Color = Color.Green;
Code language: TypeScript (typescript)
Union Types

A union type is a type formed from two or more other types, representing values that may be any one of those types. We refer to each of these types as the union’s members. For example,

let id: number | string = 10;
id = "hello";
Code language: TypeScript (typescript)

Here id is a union of number and string type. We can assign either a number or a string to the variable id.

Let’s take a look at another example. We want to create a method that combines two values.

  • If the two values are numbers then we want to add them.
  • If the two values are strings then we want to concatenate them.

For example:

combine(1, 2); // should return 3
combine("hello", "world"); // should return "helloworld"
Code language: TypeScript (typescript)

We can define the type of the function as follows:

function combine(a: number | string, b: number | string): number|string {
    // body of the function
}
Code language: TypeScript (typescript)

We know that in JS we can use the + operator to add numbers and concatenate strings. So, using that we can implement the body of the function:

function combine(a: number | string, b: number | string): number|string {
    return a + b;
}
Code language: TypeScript (typescript)

But this will give an error. Why?

The reason is the + is not valid for number | string. So, the solution is narrowing the union with type guards. We can use typeof to narrow the union. So, the final code will look like this:

function combine(a: number | string, b: number | string): number|string {
    if (typeof a === "number" && typeof b === "number") {
        return a + b;
    }
    return a.toString() + b.toString();
}
Code language: TypeScript (typescript)
Literal Types

In the case of literal types, we just don’t specify the type of value that a variable can hold, instead, we are very specific about the value that the variable can hold. To understand in a better way, write this code in the script.ts file:

let hello : "Hello" = "Hello";
hello = "Hello" // no error
hello = "World" // will give an error saying "Type '"World"' is not assignable to type '"Hello"'"
Code language: TypeScript (typescript)

In other words, here the variable hello can only hold the value "Hello". If we try to assign any other value, we will get an error.

Let’s take a better example. We have a method htmlEncode that takes two parameters a string and a style. The style can be either "bold" or "italic". We want to return the HTML encoded string with the specified style. For example:

htmlEncode("hello", "bold"); // should return "<b>hello</b>"
htmlEncode("hello", "italic"); // should return "<i>hello</i>"
Code language: TypeScript (typescript)

We can define the type of the function as follows:

function htmlEncode(text: string, style: "bold" | "italic"): string {
    // body of the function
}
Code language: TypeScript (typescript)

Here the variable style can have only two possible values "bold" or "italic". If we try to assign any other value, we will get an error.

Try to complete the function htmlEncode in the script.ts file. Here is the solution:

function htmlEncode(text: string, style: "bold" | "italic"): string {
    if (style === "bold") {
        return `<b>${text}</b>`;
    } else {
        return `<i>${text}</i>`;
    }
}

console.log(htmlEncode("Hello World", "bold"));  // <b>Hello World</b>
console.log(htmlEncode("Hello World", "italic");// <i>Hello World</i>
Code language: TypeScript (typescript)

Here is the beauty of Typescript and how it makes development easier. While writing the checks, we can see the possible values of style in the editor itself. This is not possible in JS.

Type Aliases

In the previous example, we used the type "bold" | "italic" in multiple places, then it would have been a pain to write it again and again. So, we can use type aliases to define a type and use it wherever we want. For example:

type Style = "bold" | "italic";

function htmlEncode(text: string, style: Style): string {
    if (style === "bold") {
        return `<b>${text}</b>`;
    } else {
        return `<i>${text}</i>`;
    }
}
Code language: TypeScript (typescript)

This just doesn’t work for literal types, it can work for any primitive types, object types, union types, etc. For example:

type Person = {
    name: string;
    age: number;
    id: number | string;
}
Code language: TypeScript (typescript)

NOTE: type doesn’t exist in JS. It is just a Typescript feature.

Void

This is used to represent the absence of any type. You might be familiar with void from other programming languages like C++, and Java. JS doesn’t have anything like void. But let’s say we have a function that doesn’t return anything. We can set the return type of the function as void. For example:

function printHello(): void {
    console.log("Hello");
}
Code language: TypeScript (typescript)
Any

This is used to represent any type. For example:

let a: any = 10;
a = "hello";
a = true;
Code language: TypeScript (typescript)

The only place we might use any is when we don’t want any type checking. For example, we are using a library that doesn’t have types. In that case, we can use any to avoid errors.

Unknown

Typescript 3.0 introduced a new type called unknown. This is similar to any but it is safer and less permissive. For example:

let a: unknown = 10;
a = "hello";
a = true;
Code language: TypeScript (typescript)

This looks exactly the same as that of any. But there is a difference. If we try to assign a to a variable of type number, we will get an error. For example:

let a: unknown = 10;
let b: number = a; // will give an error
Code language: TypeScript (typescript)

Whereas, if we define a as any instead of defining as unknown we won’t get any errors. For example:

let a: any = 10;
let b: number = a; // no error
Code language: TypeScript (typescript)

With the unknown, we need extra checks to make sure that the value is of the type we want. For example:

let a: unknown = 10;
if (typeof a === "number") {
    let b: number = a; // no error
}
Code language: TypeScript (typescript)

Conclusion

In this article, we learned about the basic types of Typescript. We also learned about union types, literal types, type aliases, void, any, and unknown. By this point, you should be able to write basic Typescript code.

Sharing is caring

Did you like what Arnab Sen wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far