Typescript basics for beginners

Photo by Ferenc Almasi on Unsplash

If you are new to react or have just been using react for a while you might have heard the term Typescript at least once. In this article, we are going to shine some light on the topic of Typescript so any person that is curious about it at least understands a little more after this read.

What is typescript? you might be wondering. Well, Typescript is a super-set of JavaScript, meaning is built on top of JavaScript, that provides additional syntax to support a tighter integration with your code editor to catch errors early inside it. Typescript then converts your code to JavaScript, which runs anywhere JavaScript runs: In a browser, on Node.js, and in your apps.

When using just JavaScript, the type of any variable is determined at runtime and this dictates what behavior and properties the variable will have. When you are the only one working on the code or it is a small project that is ok because you have all of these types and the functionality in your head, but as the team gets bigger it gets pretty difficult to maintain the code-base caused unintended TypeError introduced by the team. This is where Typescript saves the day, it understands your JavaScript and implements type inferences to give you great tooling for preventing these errors with little additional code, in other words, Typescript is Javascript that scales.

Photo by David Pupaza on Unsplash

The most common use for Typescript is with React. To create a react application that uses typescript, you create it as you normally would and add the --template typescript option to the command, this will set all that you need to start using typescript. You will notice that you have the regular files in all react applications but instead of those files being .js now they are .tsx indicating that the project is using typescript, and you will also have a new file in the root folder for the project called tsconfig.json, where you can control how typescript is going to be used and complied.

If you already have a project created and want to add typescript to it you just have to install the packages described in the react typescript documentation.

Let’s get started with the basics of Typescript. Typescript forces you to explicitly define the type of any variable that you are declaring, receiving as an argument, or returning from a function to prevent any bugs or confusion by using a variable in an unintended manner.

Photo by Ilya Pavlov on Unsplash

Typescript has several basic types that are the most used when programming, called primitive types. These types are the same types that the typeof Javascript operator is able to return.

  • string: represents strings of characters.
  • boolean: has 2 values, true and false, to represent a state.
  • number: This is to represent any number. Since Javascript doesn’t have any runtime value to differentiate integers from float numbers, everything is a number type.

To define the type of a variable, just declare it like you normally would in Javascript and then put a colon in front and set the type it is going to be.

You can also declare arrays of primitive types by putting the square brackets in front of the type.

You can also create arrays in which each position has a different type, you can do this by specifying the type inside the position.

For objects, there are two ways of declaring them: The first one is directly using the type Object, but this way is not recommended because it leaves the properties of the object open to be any type without checking them. For a more rigorous checking we can use the type or interface keywords and inside define each property with its type, and then use the type to declare the object.

This way you can ensure that each property is getting type-checked and that the object has all the properties necessary to work.

If we don’t want to have all the properties of an object as required you can mark them as optional by adding a question mark after the name.

This way Typescript will only give an error if we don’t provide an age on creation, in contrast with the previous declaration that will throw an error if the name and age are not provided.

After defining an object type, either using type or interface, you can use it as any other type in typescript, think of them as custom types, so you can make an array from an object of that custom type.

If you want to have a variable that will accept or could be of different types, then you can use the union to control which types are allowed for that variable.

For functions, Typescript has two ways to declare them: One is with the type Function, for the most part, it will work.

But there is another way that is more explicit on how the function work.

Now let’s get into that situation where you don’t know the type of the variable that you are using there is a type for that, called any type, but is not recommended to use it because it is a wild card and defeats the purpose of Typescript.

Instead of using any, there is an equivalent type called unknown that will work in the same way, but it is more explicit in saying that you don’t know what type that variable is. Another equivalent to the any type that is used in the return type for functions is when you don’t know if the function is going to return anything at all or if it returns something but you don’t know which type it is, for these cases you use the never type.

Now let’s talk about Aliases. Aliases allow us to create custom types. As we have seen before there are two ways of declaring custom types:

  • type: Allows to create custom-type objects and implement other types.

In this example the objects created as T2 will have 4 properties, the properties from T2 and the properties from T1, this is the way to inherit from types in Typescript.

  • Interface: They allow for the same thing as types but the inheritance is declared differently

in this case, an employee will have the attributes of Person, and from Employee.

If you want to mix inheritance between the two aliases it can be done as well, in the same way, you inherit for the Alias that you are using.

To keep your code clean and organized, you can reuse interfaces in several parts of the application by grouping them together in a .ts file (and exporting them) and then importing them where you are going to use them.

Now we are going to dig a little deeper into React-specific topics like props and events. In React when you want to pass arguments to a component you use what is known as props, since we are using Typescript we have to define what props the component is going to receive and define the type of each prop using an interface. This allows us to keep control inside the component because we know exactly what is expected.

When the type of a prop is a function, for example, to set a state, it is better to hover over the declaration of that function to see which type is it and copy it to the prop inside the interface, because the type function is not going to work for those kinds of functions.

When you create a callback for any action you expect that an event is passed, and this event also has to have a type. There are several types that can work depending on the event that is triggered and the element that triggers it, but you can use React.SyntheticEvent for a generic event or React.FormEvent in case of a submit form event.

As a final note, when using packages that can be used with typescript, there are some additional things that you have to download in order for them to work. Generally on the npm page for the package, check for a little square next to the name in the title that indicates that the package has Typescript declarations that have to be installed to be able to use it with typescript.

Thank you for reading this article all the way to the end, I hope you have learned about the basics of Typescript and that it will help you start your journey into this world. If you liked it leave a clap and check out my other articles.

Photo by Jan Tinneberg on Unsplash










Electronic engineer and software developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Protect Your Google Maps API Key with Laravel Route Signature

How to Build an App with React + Flask

Rust Day 3: Leetcode — Merge Two Sorted Lists

Finding the Sum of All Primes Equal to or Under a Given Number in JavaScript (and Then Again in…

How To Create File Dropzone Component With React

Build a Realtime PWA with React

Getting started with Webpack 4, Babel 7 and React 16

What Can Programmers Learn From Sloths

Sloth climbing on a tree

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
Mateo mojica

Mateo mojica

Electronic engineer and software developer

More from Medium

What is React Hooks?

React hooks, a starting guide

Axios Library - HTTP Requests

Facts About React Js