Moving from JavaScript to TypeScript

JavaScript vs. TypeScript

There are quite a lot of differences between the two I will cover some of them here.

Compilation errors

TypeScript is able to flag errors in compile time during the development process. This is a really good feature because it means that you are less likely to have errors at runtime when your app has been built and is running. JavaScript is only capable of seeing these errors at runtime so you are highly likely to have much slower debugging because you are now doing more unnecessary checking. The better tooling available in TypeScript provides a far better experience when writing code.

Static typing vs Dynamic typing

JavaScript uses dynamic typing whereas TypeScript uses static typing. With dynamic typing you can reassign variables because the data type can change. This is not possible with static typing because the data type is defined meaning that if you try to assign a different data type it will show a compile error. There are pros and cons for each method.

// This is valid JavaScript code
let num = 10;
num = "10";
// You will get the error Type 'string' is not assignable to type 'number'.
let num: number = 10;
num = "10";

Describing your data using an interface

TypeScript can use an interface in the code which pretty much describes the structure of an object in the application. It defines the overall syntax that is required for the object so you can use it for documentation and issue tracking inside of your code editor.

It is worth noting that the TypeScript compiler wont convert the interface syntax to JavaScript. It is only used for type checking also known as “duck typing” or “structural subtyping”.

// Describe the shape of objects in your code.
interface Series {
id: number;
seriesName: string;
releaseDate: number;
}

// Use the interface for type checking in your object.
const series: Series = {
// The id needs to be a number
id: 1,
// The series name needs to be a string
seriesName: 'The Book of Boba Fett',
// The release data needs to be a number
releaseDate: 2021,
};

console.log(series);

Read more