Basics of TypeScript: A Practical Guide
In this article, I will explain the fundamental aspects of TypeScript with the help of some practicals.
What is Typescript (Ts)?
TypeScript is a superset of the JavaScript. It added some new features and advantages to JavaScript. It's a strongly typed programming language. However, browsers can't execute the TypeScript codes. It's a compiled language and we use the TypeScript compiler to compile the TypeScript code into JavaScript code.
Why TypeScript?
Now you know that TypeScript is a superset of JavaScript and web browsers can not execute TypeScript codes. Then why to use TypeScript? There are several reasons to use TypeScript in web applications. Some important reasons are listed below.
- TypeScript is a strictly typed language
- It avoids unwanted behaviors at the runtime (Less error-prone at runtime)
- It helps developers to use the advantages of strictly typed language (Ts) over loosely typed language (JavaScript)
- It supports the concepts of Object Oriented programming
Let's learn with practicals!!!
Prerequisites
- Node.js must be installed in your development environment. If not please download and install the latest stable version of the Node.js
- Text editor to do the coding. In this example, I use WebStorm from JetBrains. However, you can use some other editor such as Visual Studio Code as well.
Install TypeScript
Open the command prompt and use the following command to install TypeScript globally on your computer.
npm install -g typescriptCreate Simple Application
To learn Ts, let's create a simple web application project. In this project, I am going to create a simple HTML file and one Typescript file to define our TypeScript codes. An example project structure is shown below. (Structure will be updated in later sections)
Link TypeScript with the HTML
As a similar way of calling a JavaScript file, you can call the TypeScript file to your HTML page.
You may notice that, instead of calling the index.ts file, I have called the index.js file to the HTML page. Yes, it’s because browsers can not execute TypeScript codes. Now you will have a question that how to get the index.js file from the index.ts file. Yes! It's time to compile our TypeScript files.
Compiling TypeScript Files
To compile your Ts file use the following code. This command will compile your TypeScript file to a JavaScript file only once. If you make new changes in your TypeScript file, then you need to execute this command again, and so on.
tsc path_to_the_typescript_file
# example
tsc src/app/index.tsTo compile the Ts file in watch mode run the following command.
tsc path_to_the_typescript_file -w
# example
tsc src/app/index.ts -wAfter you compile the TypeScript file, you will see the compiled JavaScript file.
Configuring TypeScript Configs for the Project
We can configure the TypeScript configurations as required for our project. Run the following command to generate the TypeScript configurations file (tsconfig.json).
tsc --initUpdate Project Structure
To use the TypeScript configurations, let's re-arrange our project files and directories in a logical way. The updated project structure is shown below.
tsconfig.json File
This file specifies the root files and the compiler options required to compile the project. Please refer to more details about the tsconfig file from here. Some key configurations are described below.
- outDir — Specifies the output directory of the compiled JavaScript files.
- rootDir — Specifies the root directory of the source TypeScript files.
- target — Specifies the JavaScript version of the compiled JavaScript files.
- module — Specifies the module code version of compiled JavaScript.
- include — Specifies the source TypeScript file directories other than the rootDir.
Examples
The following example configurations are done to match our new project structure.
After setting up these configurations, no need to specify the path to the TypeScript file when compiling them. You can directly run the compile command as follows.
tsc -wThis command will compile our TypeScript files stored in the src/app/ts directory and put the compiled JavaScript files into the src/app/js directory. When you link the JavaScript file to the HTML code make sure to specify the new path.
Let's test the application via the browser.
Now the configurations are completed. We can start learning the basics of TypeScript.
Primitive Types
string, number, and boolean are the primitive types in TypeScript. The following syntax can be used to define variables with a specified type in TypeScript.
//let someVariable : type;
let age : number;
// or define and assign a value
let firstName : string = "Roy";After you specify the type of the variable, you are unable to assign a value of another type to that variable.
As a best practice, we should declare the variable with a specified type before assigning the values.
Object Types
In TypeScript we use Object Types to group and pass the data.
Figure 11 illustrates an example of an object type. From lines 9 to 13 we define the type of the object which is firstName is a string, lastName is a string and age is a number. From line number 13 to 17 we assign the values according to the type which we have defined.
Arrays
In TypeScript type of the array can be flexible (Using any type. We will discuss it later) or strict.
The above figure shows an example of a string array. As you can see we specified the array type as string, we are unable to add any other type values to that array.
Tuple
A tuple is an array with a fixed length. To use a tuple, we need to know how many items we are going to store in the tuple and their order and their types in advance.
Enums
Enums are automatically enumerated global constant identifiers. Each enumerated item has a unique identifier. This unique identifier will added by TypeScript but we can use our own identifiers as well. The “enum” keyword must used to define the enums in TypeScript.
Naming conventions with enums (These are not the rules but the conventions)
- Enum name’s first letter should be Capitalized.
- Each enum value should be defined in UPPERCASE letters
As you can see in the above figure, each enumerated item has a unique identifier, it starts with 0 and goes on. We can define our own identifier values as well.
Get Lakeesha Ramanayake’s stories in your inbox
Join Medium for free to get updates from this writer.
Based on the identifier type, we can categorize the enums into three categories.
- Numeric enums — Contains the numerical value for each identifier
- String enums — Contains string value for each identifier
- Heterogeneous enums — Can contain a mix of numerical and string identifiers. However, this type is not used in practical scenarios.
The following figure shows examples of each enum type.
You can access an enum value as follows.
Refer to more about enums.
Any Type
Any type can be used to assign any kind of value to a variable. It will prevent type-checking errors. It is not recommended to use the Any type because it reduces the advantages of TypeScript.
Union Types
In TypeScript we can assign multiple types to variables by using “Union Types”. We can define union types with the help of a pipe (“|”).
However, when using the union types we have to be more careful. Because when doing comparisons we have to first check the current variable type in the runtime. otherwise, it will give some errors.
To avoid these errors, we can check the current variable type before doing any other comparisons.
To learn the union types, let's do the following practical. First, add an HTML input tag to our HTML page.
Now you can access the input element values as follows.
Figure 21 shows how we access an HTML input element in TypeScript. Also, we parse the input element value to an integer. Then our comparison can be done because it knows that the value must be a number to do the comparison.
Literal Types
Up to now, we have defined the types of the variables. But using literal types we can define the exact value of a variable rather than its type.
The below figure shows an example of literal type. As you can see you are allowed to assign the predefined literal type values to the variable.
Type Aliases
In TypeScript we are allowed to define our own types using type aliases.
type keyword must used to define a type alias. Moreover, we are allowed to use any name for the type alias except the keywords used in TypeScript. The following code block shows the skeleton of a type alias definition.
type aliasName = typesYou may think that this is similar to the union types. Yes, but if there are multiple variables that require a similar union type in that case, you can define a custom type with a type alias and reuse it.
Functions
In TypeScript we can define the input parameter types and return types of the functions. The following example shows an example of a function.
As per the example, numberOne and numberTwo are the two function parameters and their type is number, and the return type of the function is number as well.
Function Types
As you know we can assign the functions to variables in JavaScript. So in TypeScript, we can use function types to define that kind of variable.
Figure 25 shows an example of a function type. In that figure, line 95 defines the function type. According to that type, “functionVariable” is able to store any function which has two number type inputs and returns a number type value. As you can see previously defined add() function can be assigned to that variable.
As you can see in Figure 26, we can assign a new function to our “functionVariable” because it satisfies the function type that we have defined previously.
Let's try to assign a new function which is different from our function type.
As you can see it throws an error because our new function (multiplyByTwo) is not according to the function type that we have defined.
Functions with Callback functions
Usually, we use callbacks with functions in JavaScript. Using TypeScript we can define the callback function type as well. Refer to the following example.
Line 112 to 125 shows a function with a callback. According to the function signature (line 112), it accepts an array of numbers and a callback function. That callback function’s return type is void. Line 128 shows some other function that is going to be used as the callback function. In line 135 we called our function by passing an array of numbers and the callback function.
Classes
Same as JavaScript, TypeScript fully supports defining the classes using the “class” keyword. Using TypeScript we can define the access modifiers and the type of each class property as well.
Modules
Modules are very helpful when we working on large projects. They help us to logically split our codes into separate TypeScript files. We can modularize those files according to their purpose.
examples:
- A file for network request management
- A file for DOM interactions
To enable the modules from the tsconfig.json file, uncomment the module property. While linking the JavaScript file with the HTML make sure to define the script type as “module”.
After setting up the configurations, you can use import and export in TypeScript to use modules. These are declarative, to define the relationships between the modules we use imports and exports.
Let's create a module!!
- Create a new directory inside “ts” directory and name it “classes”
- Create a new TypeScript file inside the classes directory and name it “student.ts”.
- Copy the previously defined Student class into the student.ts file.
- Make sure to add the “export” keyword in front of the class keyword. (e.g. export class Student)
- Import your Student class from the module to your index.ts file
Now you must get an error like “404 not found”.
This error occurred due to the import of the TypeScript module. Because at the runtime JavaScript is trying to load the module from the TypeScript file. To avoid this error we have to import the JavaScript module to the TypeScript file when importing a module.
Please refer to more details about modules here
Generic Types
Generic types enable flexibility in the code because they allow to passing of dynamic types. Because of that instead of defining a single component for each, we are able to use one single component that allows the type that we specify while using.
Figure 36 shows an example of using generics. Line 148 shows the way to pass a generic property type to a Class. Line 158 shows the way to pass a generic parameter to a function. Finally, line 164 and 165 shows two examples of passing different values as generics to the same function and Class. Learn more from here.
Unknown Type
This type is similar to the “any” type but much safer than “any” type. Because it does not allow to do anything with an unknown value. You have to explicitly check the variable type before doing anything.
That concludes the basis of TypeScript. Hope you have gained some knowledge about the basics of TypeScript.
Have a nice day!!!









