TypeScript: Boost Your Code Quality
Why you should start coding with this language and how to get started.
I first ran into TypeScript during one of the projects I worked on at Flux IT. Particularly while working on a project for the tourism industry, where we used the MERN stack: Mongo DB, Express, React and Node. Up until that moment, I had only read comments and stories in which problems were solved because of this technology.
TypeScript came into play because the project had a major growth compared to its life cycle, and that had caused many code errors, as well as malfunctions. Therefore, in that context, it was implemented to create a more solid and stable app.
Type…what?
TypeScript is a typed programming language that compiles JavaScript Vanilla, developed and supported by Microsoft, and it can be used for both frontend and backend.
Using it allows the code to be neater, and thus, it helps us detect errors before compiling, avoiding scalability and code maintenance issues.
The shift from JavaScript to TypeScript is simple and it doesn’t bring about many complex situations, but we must pay attention to some details that we used to ignore when it came to coding: there are data or structures in JavaScript Vanilla that are now necessary with TypeScript, and these are precisely the changes that prevent future errors.
If like me, you only heard about this language recently and never really delved into it, I encourage you to try it, because it’s friendly and it’s an addition to coding good practices. In my case, If I had known about it before, I wouldn’t have spent so many hours trying to solve issues with JavaScript.
Below I share a tutorial, based on my experience, for you to take your first steps in the TypeScrip world!
Quick Set Up
Before getting started with TypeScript, there are two previous steps. First, we need to install Node JS on the official website, and then, we need to run the following command line:
npm install -g typescript
To check whether it’s properly installed, you can run the following command line and you should see the following version as an answer:
tsc -v
Now that we’ve installed TypeScript globally, we can use the TSC (Command-line TypeScript Compiler), which allows us to compile any file from TypesCript to JavaScript Vanilla.
We create a file called main.ts
which is where we’ll run our TypeScript code tests.
To use this command, we simply write tsc
followed by the name of the file with the .ts
extension on our terminal.
Since we have a main.ts
file, we’ll have the following command line:
tsc main.ts
Thus, we’ve compiled our TypeScript code and we should see that a new file with the same name but a .js
. extension is created.
Following the previous example, the new file is called . main.js
and inside it we’ll find our TypeScript code compiled to JavaScript Vanilla
Data Types
Variables
In TypeScript, variables are declared with the type of data they’ll receive when they are initialized.
let myAge: number = 22;
let color: string = 'blue';
let isDone: boolean = true;
let anyValue: any = "32"
Enum
It’s a structure of valid values that helps define a collection of data types in a precise way. For example, a list of constants.
enum daysOfTheWeek {
monday = 'Monday',
tuesday = 'Tuesday'
wednesday = 'Wednesday',
thursday = 'Thursday',
friday = 'Friday'
}
Array
Like variables, array
must be declared with the type of data they’ll store followed by []
.
let numbers:number[] = [1,2,3,4,5];
let colors:Array<String> = ['blue','red','yellow'];
Functions
In the case of functions, parameters must indicate which type of value they’ll receive and return once the function is executed.
function buildMessage(nombre: string): string{
return 'Hi ' + nombre;
}
if the function has no return value, it must be declared as :void
.
function sayHello(nombre: string): void{
console.log('Hi ' + nombre);
}
Objects
Objects in TypeScript are created in the same way as in JavaScript. The only difference is that an object must be declared with the kind of data each property will have.
let person:{name:string, hobby:string, saludar():void}= {
name: 'cris',
hobby: 'programming'
saludar() { console.log('Hi ' + this.name); }
}
Type
In TypeScript, type
defines the structure of data types and methods it must return. If any of the properties are not met, the code simply won’t be compiled.
A bonus: they can be reused several times so that we don’t have to repeat the data types.
type Person = {
name: string,
hobby: string,
saludar() => void
}let person1:Person= {
name: 'Jhon',
hobby: 'programming'
saludar() { console.log('Hi ' + this.name); }
}let person2:Person= {
name: 'Tony',
hobby: 'programming'
saludar() { console.log('Hi ' + this.name); }
}
Interface
Interfaces are defined in the same way as type
, except that they are used with the reserved word interface. Their objective and use are similar: they define the structure and methods to be implemented. As with type
, if any of these values is not met, the code won’t be compiled.
interface Person {
name:string,
hobby:string,
}let person1:Person= {
name: Cristhian,
hobby: programming
}function buildMessage(person: Person): string{
return 'Hi ' + person.name;
}
Types or Interfaces?
type
and interface
are used in a similar way. Many of the things that can be done with interface
are also possible with type
. However, we must take into account that once a type
is defined, we cannot add more properties to it, whereas interface
allows us to extend its properties as required.
Let’s take a look at the differences when trying to extend a type
or an interface
using the following examples:
interface dog{
nombre: string;
}
type cat = {
nombre: string;
}
To extend an interface
we must use the reserved word extends
followed by the name of the interface
whose structure we want it to get.
interface Auto extends Transporte {
ruedas: number;
}
As we’ve seen before, type
doesn’t allow extensions. Therefore, we must create a new type
in the following way:
type newCat = cat & {
color: string;
}
Now it’s your turn!
Learning how to code with TypeScript was challenging, but I knew that it was the next step in my growth as a Web Developer. As in any learning process, I stumbled over a few times and had to think about the issue ahead.
Eventually, I managed to understand it and overcome my hesitations, paying attention to TypeScript error messages, which always offer a solution.
If you are about to start using this language, my advice is: be patient until you fully take in the whole theory and use cases, because that’s when you’ll begin to enjoy it.
From theory to practice, TypeScript offers a major improvement regarding clean code and code quality (it’s a pity that it’s not natively included in the browser and that we have to add it to the project on our own).
Learning how to code with TypeScript will not only open your mind to a better code quality, but it will also allow you to gain knowledge and opportunities, since the best projects (the most robust ones and with years of development) are written in TypeScript.
Will you give TypeScript a try? Here’s my email in case you need a helping hand: cristhian.pabon@fluxitsoft.com.