A complete information to Typescript for JavaScript builders

If you’re a JavaScript developer, you must have heard of Typescript at one point or another. If you hated to try Typescript because you’re unsure how it could serve you better than JavaScript, you’ve come to the right place.

This guide provides an introductory but comprehensive guide to Typescript that any JavaScript developer would need to get started.

What is Typescript, what is its type system and how would you as a JavaScript developer benefit from using Typescript in your next project? Answers to all of these questions can be found at the end of this article.

Note: I may be a little biased towards Typescript. There is no project where I prefer JS over Typescript.

What is typescript?

You can think of Typescript as a language that offers an extra layer over JavaScript.

Why?

Although we write our code in Typescript initially, we cannot run Typescript directly in a browser like JavaScript. Instead, Typescript goes through an additional compilation step to convert its code into JavaScript that is recognized by the browser.

Even if we program in Typescript, the end program that is executed in the browser is executed in JavaScript.

Then why do we use Typescript at all?

Although Typescript does not offer any functionality beyond JavaScript at runtime, it does offer a number of functions to ensure that we as developers can write less error-prone and more maintainable code than if we were just using JavaScript.

How does Typescript do it?

Typescript, as the name suggests, introduces a type system via vanilla JavaScript. While the variable type is assigned dynamically in JavaScript, Typescript forces us to define the type of the declared variable in advance.

With JavaScript we can assign an integer value to a variable on the first line and assign a string value on the next line.

With Typescript, however, we can limit this behavior by explicitly declaring a type for a variable. If we try to assign a string to a variable of type “number”, an error is generated.

VS code warning in the event of incorrect type assignment

In short, this is what Typescript does differently than JavaScript: use types to prevent us from making silly mistakes in our code.

How Typescript improves JavaScript

While the inability to define types isn’t necessarily a deficit in JavaScript, it does give programmers too much freedom, which inevitably leads them to write bad code.

In the above scenario with Javascript, nothing prevents the developer from using that a number variable represent an object. While it’s not a bug that would crash the program, it goes beyond the purpose of using variable names to document the code itself.

Typescript easily solves this problem by defining the type of the variable during the declaration so that it cannot be assigned a value of any other type.

If another developer has access to this variable in your program, they can now rest assured that its value is a number that exactly matches its name.

In this case it is isEligible function expects an object with a field named age. However, Javascript cannot guarantee that the argument passed to the function is actually an object or field named age.

Here, too, Typescript has the solution to this problem.

This code may not make sense to you at this time. However, note how it ensures that the type of variable passed is of type Person, which is defined at the beginning.

Using Typescript will remove hundreds of negligent coding errors from your program and you won’t have to work your hair out every time you run into the silliest mistakes. In addition, your code will be better self-documented and maintainability improved.

If you’ve been frustrated with the inadequate JavaScript code suggestions in an IDE, you have yet another reason to try Typescript. The presence of types gives Typescript the ability to display better code suggestions in an IDE.

Using types with typescript

Basic types

Typescript has a number of basic types that are predefined. Number, string, boolean, and array are some examples.

The full list of basic types can be found in the Typescript documentation.

Here are some examples:

Notice how each type resets Typescript to act like JavaScript. Since our purpose in using Typescript is to give our code better structure, avoid using types whenever possible.

Similarly, try to avoid using a union of types. However, if this is unavoidable, limit the number of types allowed in the union as much as possible.

Declare custom types

Do you remember how I used a type called Person in a previous code example? Person is not a basic data type in Typescript. I created the person type as per my requirements to be used as a parameter type accepted by the specified function.

We use interfaces to define the basic structure of a new type that we introduce into the application.

Now when we create a new type object it should contain the field name and age. If not, Typescript throws an error.

VS Code warning of missing properties in custom types

You can also define optional fields within an interface.

You can then use a custom type as the field type when defining a different type.

Expand interfaces

In Typescript, you can inherit the properties of another type by extending its interface.

For example, suppose your application requires two different types: Person and Employee. Since an employee is also a person, it makes sense to inherit the properties of the person type when creating the employee interface. It prevents code repetition.

You can do this quickly by expanding the person interface.

Function parameter types and return types

Similar to variable types, you can define types for function parameters and return values. While the parameter type is declared next to the parameter name, the return type is declared immediately before the curly braces.

With the defined parameter type and return value, we can guarantee that you or anyone else using this function will not inadvertently pass an object that does not have the properties of the vehicle type.

You can also guarantee that the field sold in any object passed will not be undefined or null. It also eliminates a number of scenarios that could cause an error at runtime. If you’re using Javascript, you’ll need to write more code to prevent such an error from occurring at runtime.

Similar to variables, you can define the return and parameter types as a union of several types.

If you declare the accepted parameter or return type, objects of types that extend the interface of the initial type are also accepted as an argument or return value.

Use generic drugs

With Typescript you can define generic variables just as easily as before. If you define a generic function, you can use it to process data that is of one of the built-in or user-defined types.

What if you use the “any” type instead of generic?

Of course, you can modify the above function to accept all kinds of arguments of type ‘any’.

However, this method does not retain the data type passed to the function. Instead, it records any argument passed as belonging to any type. Also, you should avoid the use of any.

With generics, however, you can keep what type of data is passed to the function. If you want to change the functional logic according to the type of data being passed, then using generics is better than accepting data of any type.

Use of type aliases

If a particular field that you want to use in your application can be one of several types, you can define its type as a union of these separate types.

Now you don’t have to use a long union of types. In the future, if you want to change the return type of the function, all you have to do now is change one line of code.

Type conversion

When one type is defined by extending the interface of another, the relationship generated between the two gives us permission to convert objects defined in one of them to another.

Take the previously defined Car and ImportedCar types. First I create an object of type ImportedCar and see how the conversion works on it.

This code will compile without errors. It makes sense that this conversion works, as the ImportedCar type already has all the fields defined in the Car type.

If we try to access the manufacturer field defined in the object before conversion, an error is generated because the converted object is of type Auto.

Conclusion

I hope this post has cleared up any doubts you had about using Typescript for frontend development. Since most of the functions in Typescript are already similar to JavaScript, you can master Typescript in no time. It would definitely pay off in your next project.

And the next thing you know would be that you will become a JavaScript developer who cannot live without Typescript like me.

These items was originally published on Live code stream by Juan Cruz Martinez (Twitter: @bajcmartinez), Founder and publisher of Live Code Stream, entrepreneur, developer, author, speaker and maker of things.

Live code stream is also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI and computer science in general.

Comments are closed.