Introduction
When I first started using TypeScript I have to admit, I wasn't a fan of all the restrictions. I was used to the freedom of JavaScript, where I could do pretty much whatever I wanted with my variables. I remember thinking to myself, "Geez, maybe Microsoft should have called it TypeStrict instead of TypeScript." But as I kept using it, I started to see the benefits.
JavaScript
is a programming language that is commonly used for building web applications. It has proven popular for developing both small and large-scale applications, and it has a strong developer community that creates tools and frameworks to help developers build scalable and maintainable systems. However, Microsoft recognized that JavaScript
has limitations when it comes to constructing complex, large-scale applications and to tackle these limitations, Microsoft created TypeScript
, a language designed by TypeScript's
lead architect, Anders Hejlberg.
Think of TypeScript as the ultimate JavaScript upgrade. It was officially released in 2012 and it takes all the nice stuff from JavaScript and adds a host of other features that make it even more powerful. While the release of ES6 has addressed many of the concerns people had with JavaScript, TypeScript is still a go-to choice for many developers since it offers some great features, such as interfaces, type safety and many more.
In this article, we'll delve into the fantastic world of TypeScript
and examine all the cool ways it can improve your code. From basic types to type aliases, we'll cover all you need to know to boost your type safety and avoid pesky runtime errors.
Getting Started with TypeScript
To get started with TypeScript, you simply need to install Node.js (a JavaScript runtime) and Typescript compiler on your computer and you'll be ready to start writing and compiling TypeScript codes in no time! To install the TypeScript compiler on your computer, simply run the command in your command prompt:
npm install -g typescript
Great! You can now choose to use any preferred code editor to create a basic typescript project. Similar to how JavaScript files have extensions like .js, TypeScript
files extension is ‘.ts’. Once you have a few written codes in your index.ts file you’d have to compile. Simply navigate to the directory containing your TypeScript file and run the following command:
tsc index.ts -watch
This will compile your index.ts file into a JavaScript file with the same name. You can then use this JavaScript file in your web projects just like you would use any other JavaScript file.
Basic Types in TypeScript
One of the key features of TypeScript is the usage of strict types, which allows developers to specify the data type of a variable when it is declared. This helps to detect bugs early on and can make it easier to comprehend and work with large codebases.
In TypeScript, there are three primitive types: string, number, and boolean. A string is used to represent text, such as characters or words. A number indicates numerical quantities, such as 88 or 3.142. A boolean is a type that can have one of two values: true or false. Variables may or may not have their types explicitly defined, but once a variable is assigned a type value, its type is fixed and cannot be changed. Let's take a look...
let firstName = 'Analiese';
console.log(`hi ${firstName}`)
The variable firstName has been assigned the type string, and attempting to reassign it to a value of a different type, such as a number or boolean, would result in an error. While this approach assures type safety, it can hinder code readability in large-scale systems. To fix this, we must explicitly define our variables.
let firstName:string = 'Analiese';
let age:number = 10;
let answer:boolean = true;
console.log(`${firstName} is just ${age} but it was ${answer} that she bullied kids at school`)
You can explicitly define the type of a variable by putting the type after a colon next to the variable name. This enhances code readability and helps others understand the intended types for variables, making it easier to spot bugs.
Object Types in TypeScript
Arrays and Objects in JavaScript are like boxes. They can store any sort of value and be accessed quickly using an index number or by using a ton of methods. As you progress in your understanding of TypeScript, it is important to become familiar with the use of Arrays and Objects.
Let’s try to explicitly define an Array in TypeScript
by specifying the type of elements that can be stored in that Array. Check this out:
let colors:string[] = ["red","blue","yellow"]
colors.push('black')
//Type 'number' is not assignable to type 'string'
colors.push(4)
console.log(colors)
In this example, we defined an array called "colors" to only contain strings (color names). This array also accepted a ton of other data that were of the type string but when you try to push a number to the array, you will get a TypeScript
error saying “Type 'number' is not assignable to type 'string'”. So, TypeScript
does have its way to keep us type safe.
Defining types for keys in an object is easy in TypeScript
. Just specify the type for each key and you're done. It's similar to how you define types for variables. Let's dive in and see what all the fuss is about.
let profile: {
name: string,
age: number,
address: string,
phoneNumber: number
};
profile = {
name: "Steph",
age: 11,
address: "Newyork",
phoneNumber: 2201846637
};
console.log(profile)
Once you define the keys for an object in TypeScript, you won't be able to add or omit keys, and you also won't be able to change the data type of the keys. This helps ensure that the structure of the object remains consistent and that there are no type errors in your code.
Although defining types for objects can seem like a hassle, it's actually incredibly helpful. It helps you write cleaner and more reliable code, and it can prevent a lot of bugs in the long run, which will save you time. So, even though it may seem like extra work at first, it's worth it.
Union Type in TypeScript
Sometimes, you may not want to limit variables to a single type because they can undoubtedly change. So, what to do then? You can use the Union type with TypeScript
. For example, if you have a user id key in an object, it could potentially be a number or a string. By using the Union type, you can easily handle both instances.
The Union type syntax is a way to tell TypeScript
that a variable could be one of several types. So, if you've got a variable that you're not sure about, just use the Union type syntax and you'll be good to go. Let’s see how it works:
let userProfile:{
name:string,
userId:(string|number)
age:number,
address:string,
phoneNumber:number
}
userProfile = {
name:'Steph',
userId: '2a43h4',
age:20,
address:'New york',
phoneNumber:222099292
}
console.log(userProfile)
userProfile.userId = 2865356
The userId key is flexible, as it can contain either a string or a number. This is similar to the OR operation, where you can pick either option.
Any Type in TypeScript
The any type in TypeScript
is basically a way to tell the compiler, "Hey, I don't know what type this value is going to be, and that's okay." It's kind of like a wild card - you can assign it any value you want, and it will accept it without complaining.
let value: any[] = ["milk", 8644, "hello", true, 23];
value.push("Steph");
value[6] = 23;
console.log(value);
However, it's important to be careful with the any type, because it does take apart the whole concept of TypeScript
and it can lead to issues at runtime. So, It is generally a good idea to use the any type sparingly and only when it is genuinely necessary.
Type Aliases
You might find yourself repeating the same types over and over again and you might not want to do this. With type aliases in TypeScript
you can avoid this.
Type aliases are like little shortcuts for your types. You can define a type alias for a complex type, export and use it whenever you want to refer to that type. It's kind of like giving a type a nickname, so you don't have to keep typing out the whole thing. Let's have a look at some examples to see what I mean.
type userid = string | number;
const LogOut = (id: userid) => {
console.log(id);
};
const LogIn = (id: userid) => {
console.log(id);
};
LogIn(2343);
LogOut("2343");
By using an alias called userid, I can define a type that can hold either a string or an integer value and reuse it just anywhere in my code. This enhances the readability and maintainability of my code and if I needed to make changes to the userid type, I'll only need to make changes to the userid alias declaration instead of searching and replacing the types throughout the entire codebase.
Conclusion
TypeScript is fun and as a JavaScript developer, you might want to see what it can do for you. With its strong type system and all the added features that TypeScript gives, you'll have everything you need to build large-scale, complicated applications with confidence. So, don't be scared! Embrace the TypeScript life! As you might just need it to take your development process to the next level.