2021-06-15
I have been using JavaScript for quite some time now, and recently I started using TypeScript in my projects. TypeScript is basically JavaScript with types. It was developed by Microsoft and it compiles down to plain JavaScript.
The main reason I started using TypeScript is because it helps catching errors early during development. In JavaScript, we can assign any value to any variable, and we will only find out if something is wrong when we run the app. With TypeScript, we get errors in the editor before we even run the code.
For example, in JavaScript we can do something like this:
let price = 100;
price = "free";This is valid JavaScript, but it can cause unexpected behaviour later in the code if we try to do calculations with price. In TypeScript, once we declare price as a number, we cannot assign a string to it.
TypeScript has several basic types that we use frequently:
string for text values, number for numeric values, boolean for true or false, array for list of values, and any which basically means it can be anything, similar to normal JavaScript.
let name: string = "David";
let age: number = 25;
let isActive: boolean = true;
let scores: number[] = [90, 85, 92];One of the features that I find very useful is interface. We can define the shape of an object using an interface. This is helpful when we are passing data around, because we know exactly what properties are available and what types they are.
interface User {
id: number;
name: string;
email: string;
isAdmin?: boolean;
}The question mark on isAdmin means that property is optional.
We can also define types for function parameters and return values. This makes it clear what the function expects and what it gives back.
function calculateTotal(price: number, quantity: number): number {
return price * quantity;
}If we try to call calculateTotal("ten", 5), TypeScript will show an error immediately.
To start using TypeScript in a React project, we can use npx create-react-app my-app --template typescript or if we already have an existing project, we can install TypeScript and rename our .js files to .tsx for React components or .ts for regular files. It does take some time to get used to, especially when dealing with complex types, but the benefits are worth it. Our code becomes more predictable and easier to maintain.