JavaScriptT Dark_870x220

The web has evolved so fast throughout the years. First, we learned about HTML and CSS, and also how to style our pages. Then we needed to give movement to our pages, and then came JavaScript. In the beginning, it wasn't so easy and beautiful to work with like it is today, and a lot of people didn't have confidence in the language. We were always looking for the best practices to work with JavaScript because it wasn't so easy like it is now.

Then, after a time of hard work and community growth, JavaScript took over the world. A lot of frameworks have been made, a lot of libraries have been created, and the language has evolved as well, with a lot of specifications as ES2016 or ES2017. We started to use JavaScript on the server side as well, and today a lot of applications use JavaScript for both frontend and server side.

In JavaScript, we cannot work with types like Java or C#. For a long time that was a con because a lot of developers were used to those, so they didn't migrate to JavaScript right away because they didn't feel safe enough.

TypeScript came to solve this problem for us, by letting us work with types in JavaScript. This can lead us to better code that is more readable, safer, and without nonsense errors that we might face within the development of applications.

What and Why

JavaScript really changed our world and made it possible for us to write better applications. We started to use it at the front and server side, and a lot of libraries, frameworks, applications, companies were made because of JavaScript. But with JavaScript, when we're working with really huge codebases, it tends to let our code get messy if we don't take caution, with a lot of bugs and difficulty debugging it. That's why Microsoft created TypeScript, and a lot of developers adopted it in their projects.

TypeScript is a superset of features that enable us to use types in JavaScript. It gives us a module system, classes, interfaces, and a rich type system. TypeScript helps us write better code, with fewer errors, helping to catch mistakes statically that we can commit along the way while we're building our applications. We can enhance the code quality and understandability of our application just by starting to use types in our code.

Basically, what TypeScript does is that it will compile the code and generate a compilation of errors if it finds syntax errors, like misspellings. With that, it gives us a lot of safety when writing our code.

So, let's dive now in TypeScript and learn its basics, starting with Variables. To start to work with TypeScript quickly, we can use the TypeScript Playground for it, just for learning purposes.

TypeScript Playground

Variables

Any piece of JavaScript is a TypeScript valid code, so when you're declaring a variable in TypeScript, all you need to do is include a colon (:) after the variable name. You can give it any type you want. In TypeScript, we have these basic types: any, number, boolean, string, undefined, object types and void.

So, let's imagine that we want to create a new const called User, and we want it to be a string, so it would be like this:

const User: string = "Leonardo";

We can pass it any type we want, as long we pass the value of the same type; otherwise, it'll throw an error. For example, if we want our const to be string, and we pass a number to it, it'll throw an error:

const User: string = 21;

This line will generate an error: Type '21' is not assignable to type 'string'.

We can pass any basic type we want to variables in TypeScript:

const User: = "Leonardo";
const UserAge: = 21;
const IsDeveloper: = true;
const hobbies: [] = ["Futebol", "Coding"];

Also, we can pass object types to variables in TypeScript. Let's imagine that our User would be an object with the following properties:

  1. name should be a string;
  2. age should be a number;
  3. isDeveloper should be a boolean;

How we could create a type for it? Well, we could create an interface or a type for it. Let's learn more about these powerful object types in TypeScript and see how they work.

Interfaces and Types

You can imagine an interface as a set of related properties and methods that describe a specific object. But, in TypeScript, interfaces are just a virtual structure that only exists within the context of TypeScript. They're created just for type checking our code and to see if everything's working fine. Now, we can write the following code to create an interface for our User:

interface User {
  name: string;
  age: number;
  isDeveloper: boolean;
}

Now, we can replace the string type in our User variable to be a User. This will generate an error because we're assigning a string where it should be an object containing those three properties that we create in the User interface. Let's fix this code:

const User: User = {
  name: "Leonardo",
  age: 21,
  isDeveloper: true
};

Another thing that we can do with an interface in TypeScript is passing an optional value. Let's imagine that we want the isDeveloper property to be optional. All we need to do is pass a question mark (?) before the colon (:):

interface User {
  name: string;
  age: number;
  isDeveloper?: boolean;
}

We can also pass functions to an interface, like this:

interface User {
  name: string;
  age: number;
  isDeveloper?: boolean;
  renderName?: (name: string) => string;
}

Types and interfaces in TypeScript are pretty similar, but they have some differences. To create a type, all you need to do is:

type Book = {
  title: string;
  author: string;
  year: number;
}

One of the differences between a type and an interface is the functionality of extending. With an interface, we can create a new interface and extend it, like this:

interface PremiumUser extends User {
  premiumship: boolean;
}

An interface can extend multiple interfaces and classes; a type can not. Another difference between a type and an interface is that the syntax to write a type is different. You need to include an equals sign (=) before the semicolons, like when you're creating a variable.

Intersection and Union Types

To use multiple types in TypeScript, we can use union types. Let's imagine that we want our User variable to accept a string or number, all we need to do is:

const User: string | number = "Leonardo";

Now a User can be either a string or a number. We can also use union types with types, interfaces, and classes:

interface Man {
  name: string;
  age: number;
  profession: string;
}

interface Woman {
  name: string;
  hairColor: string;
  age: number;
  profession: string;
}

type User = Man | Woman;

Functions

Each good application is composed of simple, good and pure functions. To use TypeScript in our functions is not that hard, and it'll make our code safer and more concise. Let's suppose that we have a simple function called printFullName, which is going to console a full name:

const printFullName = (firstName, lastName_) =>
  console.log(`Hello ${firstName} ${lastName}`);

Now, we can create a type called FullName and pass it to our function. We should pay attention here because in our function we're returning nothing specifically, just printing the full name in the console. So in our type, we should return void otherwise, it'll throw an error like this:

type _FullName_ = (
  firstName: string,
  lastName: string
) => void;

const printFullName: FullName = (firstName, lastName) =>
  console.log(`Hello ${firstName} ${lastName}`);

To add types in our functions we can also use an interface, like this:

interface _IFullName_ {
  (firstName: string, lastName: string): void;
}

const printFullName: IFullName = (firstName, lastName) =>
  console.log(`Hello ${firstName} ${lastName}`);

Future

As we can see, TypeScript really helps us to write better applications with cleaner code, but a lot of people have the same question in mind when it comes to type in their code: Is it worth it to learn TypeScript? Definitely, yes!

In my opinion, we'll see more and more applications being built with TypeScript, and a lot of companies are adopting it lately! Also, a lot of open-source projects are adopting it. One of the most recent and more famous was Jest - the JavaScript Testing Framework - that's a sign that TypeScript really is gaining more and more traction.

You don't need to start to use TypeScript right away and type all of your code (although it'll be pretty good). You just need to start to use it incrementally. Start using interfaces and types first, then go to intersection and union types. Soon you can use it in your functions. You'll see that it will improve a lot of your code, then after that, you can start to use more advanced concepts in TypeScript, such as Generics and Iterators. We'll get into those more in the future.

Conclusion

This is a short intro to TypeScript. In this article we learned and explored it how TypeScript works, using interfaces and types, union types, and also adding types to our functions.

To fully benefit from the power of TypeScript when writing your code, I strongly recommend you to use it in a side project first. Try to build something really simple with it - with that you can get practice and learn more about it. You can build a simple calculator or a to-do app, then start to implement it in other projects as well.

TypeScript is a super language that helps us write better, safer, and more concise code, improving our experience and removing some dumb errors that we can make along the way. Thanks for the reading!

Looking for More about TypeScript?

Want to keep diving into TypeScript? Check out these related posts to learn more.


Leonardo Maldonado
About the Author

Leonardo Maldonado

Leonardo is a Full Stack Developer, working with everything React-related, and loves to write about React and GraphQL to help developers. He also created the 33 JavaScript Concepts.

Related Posts

Comments

Comments are disabled in preview mode.