Schedule a free product or technology session with Grandmetric Engineer
schedule a video call

Blog

IP and Mobile Trends and Education

 

Basic TypeScript types



05.08.2020

To make your code more predictable and readable you can set types of your variables, functions (arguments and return values), etc.
In this post I will show you basic Typescript types and how to use them.

What is TypeScript?

TypeScript is a superset of JavaScript which provides optional static typing, interfaces, and classes.

Is TypeScript worth using? It is, although the advantages of Typescript may not be visible at first glance. TypeScript has a lot of benefits, the biggest one (in my opinion) is spotting errors by our IDE when we are writing the code. Another one is writing readable and maintainable code. It is handy when our project has a lot of lines of code, files, components, etc.

At first, I wouldn’t say I liked TypeScript at all. I felt that I was writing more code than before, which was not my intention.
But now I know, the additional Typescript syntax saved me hours that I would spend on fixing type-related bugs.

What are basic TypeScript data types?

A data type is a description type of variable, constant, argument, etc.

But why would you declare a type for a variable?
The answer is not simple, but generally, we want to have a compiler ‘over us’, which will inform us when we make a mistake.

Real world example:

Let’s declare the type of a variable for opening and closing a modal.

let isOpen: boolean = false;

Now we need a function for toggling the modal.

function toggleModal(): void {
    isOpen = !isOpen;
}
toggleModal();
console.log(isOpen); // returns true

In the example above everything is ok. However, let’s check what happens when we make a small mistake. How will the compiler react?

function toggleModal(): void {
    isOpen = 'myString'; // returns Type '"string"' is not assignable to type 'boolean'.
}

What will happen now? The IDE will tell us, ‘Hey, you made a mistake here.’

It was just a simple example, but what if your project has thousands of lines and you made a mistake without using TypeScript?
You can find this error quickly or you can waste a lot of time looking for a bug. The choice is yours.

Basic data types


Boolean:

The most simple datatype for true/false value, e.g.

let isOpen: boolean = true;


Number:

Another simple datatype, TypeScript supports decimal, hexadecimal, binary and octal literals, e.g.

let decNum: number = 5;
let hexNum: number = 0xf0dd;
let binaryNum: number = 0b1101;
let octNum: number = 0o777;


String:

Fundamental data type, in this case, we need to remember that we must declare string type by the lowercase letter. Why?

The String is the JavaScript String type, which you could use to create new strings, e.g.

const myStr = new String(‘foo bar’);

The “string” (by the lower case) is the TypeScript string type, which you can use to type variables, e.g.

let myStr: string = ‘foo bar’;


Array:

An Array type is simple, but we have two ways to declare the type, e.g.

In this case, we will declare an array of numbers.

First way:

let list: number[] = [1, 2, 3];

Second way:

let list: Array<number> = [1, 2, 3];

Most of the people prefer the first way 😉


Tuple:

A Tuple is a very useful type. With a tuple we can define an array with a fixed number of elements. Elements in the Array must be typed, e.g.

let myTuple: [number, string, boolean, string];

And we can use it like this:

myTuple = [1, 'mystring', true, 'mystring2'];

In heavily typed languages(e.g. C++) tuples can improve the performance of our code.

BONUS: React Hooks returns tuple!

const [isOpen, setIsOpen] = useState(false);


Enum:

With enums we can declare a set of named constants. Enum values start from zero and increment by 1 for each element, e.g.

enum FrontendFrameworks {
    React,
    Vue,
    Angular,
    Svelte
}
FrontendFrameworks.React // returns 0
FrontendFrameworks.Vue // returns 1

But, also we can declare the start number of increment, e.g.

enum FrontendFrameworks {
    React = 2,
    Vue,
    Angular,
    Svelte
}
FrontendFrameworks.React; // returns 2
FrontendFrameworks.Vue; // returns 3

We can also declare enums with string values, e.g.

enum FrontendFrameworks {
    React = 'REACT',
    Vue = 'VUE',
    Angular = 'ANGULAR',
    Svelte = 'SVELTE'
}
FrontendFrameworks.React; // return REACT
FrontendFrameworks['Svelte']; // return SVELTE


Any:

In some cases, we can’t declare the real type of our variable. Then, we can use an Any type, e.g.

let x: any = 5;
x = 'mystring';

I don’t recommend that, but as you can see, it is possible.


Void:

Void is used for declaring a function that doesn’t return value, e.g.

function foo(): void {
console.log('i don't have return value');
}

BONUS:

It’s not all! We have a lot of types in TypeScript, e.g.

In React we can declare a type for the component.

const Item: FunctionComponent = () => (
<div>Hello</div>
);

These are the basic Typescript data types. In the next post, I will show you some Advanced Types (Interfaces and more) and how you can use TypeScript with React (or even NestJS).

I hope you enjoyed this post. Good luck with using TypeScript!

Author

Kacper Malkowski

Kacper is a Frontend Developer, but he is not afraid of backend adventures. His interests include both frontend and backend development, machine learning, and astronomy.

Leave a Reply

Your email address will not be published. Required fields are marked *


 

Newsletter