Why even bother learning TypeScript?
It's a great question! JavaScript pretty much gets the job done then why bother wasting my time learning a new language again? JavaScript is already time-consuming to learn and nobody truly masters it because the language evolves at a fast pace. There are also a lot of frameworks and libraries to learn.
This is outdated thinking. If you wanna join the cool kids, start learning TypeScript today. Also, companies are looking for Developers with expertise in more than one language.
JavaScript has a fair number of flaws when compared to modern-day languages. This results in programmers hating it a lot. TypeScript has all the features JavaScript has, plus adds a new layer on the top: Types. It solves a lot of problems JavaScript has and therefore makes it a bit more developer friendly.
What are the differences between the two?
Compile-time errors
The biggest advantage of TypeScript is its ability to catch errors at compile-time, whereas, JavaScript catches errors at run-time. This can save a lot of time and effort in debugging, especially in large codebases. TypeSctipt also highlights the errors with meaningful messages to help debug them quickly.
Interfaces
In TypeScript, an interface is a way to define a contract for an object, describing the shape of the object's properties and methods without providing an implementation. It defines a set of rules that an object must follow to be considered of that interface type.
We can use Interfaces to validate the shape of an object, ensuring that it contains all the required properties and methods. This can help catch errors early on in the development process before they cause issues at runtime.
// Describe object’s shape using an interface.
interface Car {
id: number;
color: string;
owner: string;
}
// Use interface for type checking.
const honda: Car {
id: 12345, // id must be a number
color: 'White', // color must be a string
owner: 'Batman', // owner must be a string
}
Dynamic vs Static typing
In dynamic typing, the type of a variable is determined at runtime based on the value it holds. This means that a variable can hold different types of values at different times, and the type of the variable can change as the program runs. JavaScript is an example of a dynamically typed language.
// Valid JavaScript code
const x = 1;
x = '5';
On the other hand, in static typing, the type of a variable is determined at compile time, based on the way it is declared. This means that a variable can only hold values of a specific type, and attempting to assign a value of a different type will result in a type error. That's why TypeScript is called strongly typed JavaScript.
/* Not a valid TypeScript code. Error Type 'string' is
not assignable to type 'number'. */
const x: number = 1;
x = '5';
Composing Types
You can create your complex types using TypeScript by simply combining types. The two general ways to compose types are: with unions, and with generics.
Using a union, you can declare that a type could be one of many types. We can use it to describe the set of literals a value is allowed to be:
type BoxShape = 'rectangle' | 'square';
type PrimeNumbersUnderTen = 2 | 3 | 5 | 7;
Generics are used to assign specific types to other types. Arrays are the best example. By default, arrays can contain any type of data, but using generics we can specify what type of data an array can accept.
type StringArray = Array<string>;
type ObjectArray = Array<{ id: number }>;
Modules
Anyone familiar with Node.js should be familiar with the CommonJS module which uses the require
syntax. Whereas, when using Node.js with TypeScript you can use either require
or import
and export
(ES module). Although, there are ways to implement the ES module in JavaScript as well with a little bit of tweaking.
CommonJS module
const express = require('express');
ES module
import express from 'express';
Ok, but what about the drawbacks?
Yes, TypeScript might be amazing but it has its fair share of disadvantages.
One disadvantage is browsers don't support TypeScript directly, therefore it needs to be compiled to JavaScript before it can be used. Luckily, TypeScript has a compiler and it's easy to set up. After that TypeScript code is compiled automatically to JavaScript. Also, it is a fast process and therefore we don't need to wait long hours.
Another drawback is that you probably would be typing more when writing TypeScript code. Though writing more will result in a more performant and better code which is actually a plus point in the future.
Something to note is that you will probably need some Type Declaration packages alongside some of the normal packages that you use. Declaration packages will give you a way to declare types and values. Although there are packages with type definitions already there, but, this will always not be the case. One of the most popular examples is Express.
Express with JS
npm install express
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Express with TS
npm install express @types/express @types/node
import express, { Request, Response } from 'express';
const app = express()
const port = 3000
app.get('/', (req: Request , res: Response) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Good resources to learn TypeScript?
If you ask me, I am learning TypeScript using the official documentation and ChatGPT. If you already know JavaScript then it won't take you long to get the hang of it. If you are learning JavaScript, then clear the basics and wait until you have more experience with JavaScript then get into TypeScript. Use ChatGPT, it's a great tool for learning. Read the official docs. Some other resources can be courses like Learn Typescript, TypeScript Handbook, and TypeScript Deep Dive.
Conclusion
Shifting from JavaScript to TypeScript can seem intimidating at first, but it's a worthwhile investment for developers looking to take their skills to the next level. TypeScript provides a range of benefits, including better error handling, improved code organization, and cleaner code. With the right tools and resources, migrating from JavaScript to TypeScript can be a relatively painless process that can pay dividends in the long run.