The What, Why, and How of TypeScript for JavaScript Developers

A typed introduction to JavaScript

Juan Cruz Martinez
Nov 30, 2020 · 8 min read
The word “TypeScript” against a blue background
The word “TypeScript” against a blue background
Image by the author

If you are a JavaScript developer, you must have heard about TypeScript at one point or another. If you have been reluctant about giving Typescript a try because you are not sure how it could serve you better than JavaScript, you have come to the right place.

This guide gives an introductory but comprehensive guide to TypeScript any JavaScript developer would need to get started with it.

What is TypeScript, what is its type system, and how would it benefit you as a JavaScript developer to use TypeScript in your next project? You will find answers to all these questions by the end of this article.

Note: I may be a bit biased towards TypeScript. There’s no project that I start where I prefer JS over TypeScript.

What Is TypeScript?

You can think of TypeScript as a language that provides an additional layer over JavaScript.

Why?

Although we initially write our code in TypeScript, we can’t directly run TypeScript on a browser like we run JavaScript. Instead, TypeScript goes through an additional compilation step to convert its code into browser-recognized JavaScript.

So even when we program in TypeScript, the end program that runs on the browser will be in JavaScript.

Then why do we use TypeScript at all?

Though TypeScript doesn’t provide more functionalities than JavaScript at runtime, it offers a set of features to ensure that we, the developers, can write less error-prone and better maintainable code compared to when using just JavaScript.

How does TypeScript do that?

TypeScript, as the name suggests, introduces a type system on top of vanilla JavaScript. Whereas with JavaScript the type of a variable is dynamically assigned, TypeScript forces us to predefine the type of the variable we are declaring.

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

let jsVar = 0;
jsVar = "js";

But with TypeScript, we can restrict this behavior by explicitly declaring a type for a variable. If we try to assign a string to a variable of type number, it generates an error.

let tsVar: number = 0;
tsVar = "ts"; //error
Image for post
Image for post
VS Code alerting of wrong type assignment

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

How TypeScript Improves Upon JavaScript

While the lack of the ability to define types is not necessarily a deficit in JavaScript, it gives too much freedom to programmers, which inevitably results in them writing bad code.

let aNumber = 123;aNumber = {
name: "John",
age: 23
}

In the above scenario with JavaScript, there’s nothing to stop the developer from using the aNumber variable to represent an object. While it isn’t an error that would crash the program, it defeats the purpose of using variable names to self-document the code.

TypeScript easily solves this issue by defining the type of the variable during declaration so that it can’t be assigned to a value of another type.

let aNumber: number = 123;

If another developer has access to this variable in your program, they can now rely upon its value being a number, exactly as the name suggests.

In this case, the isEligible function expects an object that has a field named age. But JavaScript doesn’t have a way to guarantee that the argument passed to the function will be, in fact, an object or that it will have a field named age.

Again, TypeScript has the solution to this problem.

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

Using TypeScript will take away hundreds of careless coding mistakes from your program and prevent you from having to pull your hair out every time you encounter the silliest of bugs. It will also make your code better self-documented and increase its maintainability.

If you have been frustrated with the insufficient code suggestions provided for JavaScript in an IDE, then you have another reason to give TypeScript a try. The presence of types gives TypeScript the ability to show 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 a few examples of them.

You can find the complete list of basic types in the TypeScript documentation .

Here are a few examples:

Note how any type reverts TypeScript to behave the same way as JavaScript. Since our purpose of using TypeScript is to give a better structure to our code, avoid using any type whenever possible.

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

Declaring custom types

Remember how I used a type called Person in a previous code example? But Person is not a basic data type in TypeScript. I created the Person type according to my requirements to use it as the type of parameter accepted by the given function.

We use interfaces to define the basic structure of a new type we are introducing to the application.

interface Person {
name: string;
age: number;
}

Now, if we create a new object of type Person, it should have the field’s name and age within it. If not, TypeScript throws an error.

Image for post
Image for post
VS Code alerting of missing properties in custom types

You can also define optional fields inside an interface.

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

interface Person{
name: string;
age: number;
address: Address;
}

Extending interfaces

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

Assume that your application needs two different types, Person and Employee. Since an employee is also a person, it makes sense to inherit the Person type’s properties when creating the Employee interface. It prevents code repetition.

You can quickly achieve this by extending 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 just before the curly braces.

With the type of the parameter and return value defined, we can guarantee that you or anyone else using this function won’t accidentally pass an object that doesn’t have the characteristics of the Car type.

You can also guarantee that the field sold in any object passed won’t be undefined or null. And it eliminates a number of scenarios that could throw an error during the runtime. If you were using JavaScript, you would have to write more code to prevent the possibility of such an error occurring during runtime.

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

function buyCar(car : Car): Car | boolean {
if (car.sold === true){
return false;
}
return car;
}

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

Using Generics

With TypeScript, you can define generic variables just as easily as what we have covered so far. If you are defining a generic function, you can use it to process data that belongs to any of the built-in or custom types.

function getInfo<T>(input: T): T {
return input;
}
const stringInfo = getInfo<string>("Hello World");
const numberInfo = getInfo<number>(3321);
const carInfo = getInfo<Car>(car1);

What if you use the ‘any’ type instead of generics?

Of course, you can change the above function to accept any type of arguments using the any type.

function getInfo(input : any) {
return input;
}
const stringInfo: string = getInfo("Hello World");
const numberInfo: number = getInfo(3321);
const carInfo: Car = getInfo(car1);

However, this method doesn’t preserve the type of data passed on to the function. Instead, it records every argument passed as belonging to any type. Besides, you should avoid the use of any.

With generics, though, you can preserve what type of data is passed on to the function. If you want to change the function logic according to the type of data passed, using generics is better than accepting data of any type.

Using Type Aliases

When a particular field you want to use in the application could belong to one of several types, you can define its type as a union of those separate types.

Instead of having to rewrite the union every time, like above, you can define an alias for the union using the type keyword.

Now you won’t have to use a long union of types. Also, if you want to make a change to the return type of the function in the future, you now have to change only one line of code.

Type Conversion

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

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

This code compiles without an error. It makes sense that this conversion works because the ImportedCar type already possesses all the fields defined in the Car type.

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

convertedCar.manufacturer;  //error

This conversion works the other way around too. We can convert a Car object to an ImportedCar object.

In this case, if you try to access the new field the Car object previously didn’t have, manufacturer, you will see that it returns undefined.

convertedImportedCar.manufacturer;   //undefined

Conclusion

I hope this article cleared any doubts you had about using TypeScript for front-end development. Since most of the features in TypeScript are already similar to JavaScript, you will be able to master TypeScript in no time as well. It would definitely pay off in your next project.

And the next thing you know, you’d become a JavaScript developer who can’t live without TypeScript, just like myself.

Thanks for reading!

Better Programming

Advice for programmers.

Sign up for The Best of Better Programming

By Better Programming

A weekly newsletter sent every Friday with the best articles we published that week. Code tutorials, advice, career opportunities, and more! Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Juan Cruz Martinez

Written by

I’m an entrepreneur, developer, author, speaker, and doer of things. I write about JavaScript, Python, AI, and programming in general.

Better Programming

Advice for programmers.

Juan Cruz Martinez

Written by

I’m an entrepreneur, developer, author, speaker, and doer of things. I write about JavaScript, Python, AI, and programming in general.

Better Programming

Advice for programmers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store