TypeScript basic types with examples

Recently, I’ve had the opportunity to play with TypeScript at the workplace. At first, I found the JavaScript code hard to follow because of the type declarations. But very soon I fell in love with it because of its usefulness. It hasn’t been a smooth ride though. I’ve faced challenges in stuff like declaring an array of strings and the list goes on. This post is a collection of the frequently used basic types I’ve come across so far.

What is TypeScript

In JavaScript, it’s not possible to set the type manually. For example, you declare a variable but can’t specify that the variable should take string only. And how cool it would be if we try to assign a number to that variable, we get notified during compilation.

TypeScript provides static typing to JavaScript by allowing us to set the types. It will yell in compile-time if you don’t provide the value of appropriate types which is very helpful to avoid some of the common bugs. Let’s jump on the different types and how we can declare them.

You can try the below examples in the TypeScript playground.

Number

We can decalare a variable to be type of number the following way.

const aNumber: number = 10;

/*
  will throw error for other types of values
*/
const aNumber: number = 'notANumber'; // Type '"notANumber"' is not assignable to type 'number'.

String

A variable to be type of string the following way.

const aString: string = 'ten';

/*
  will throw error for other types of values
*/
const aNumber: string = 10; // Type '10' is not assignable to type 'string'.

Boolean

Boolean values are either true or false.

const aBoolean: boolean = true;

Array

We can declare an Array type in two ways. Also, it’s possible to declare array element types. We want to say that the variable is an array of certain types.

/*
  using type of elements followed by []
*/
const anArray: number[] = [1, 2, 3];

/*
  using generic array type
*/
let anArray: Array<number> = [1, 2, 3];

How do we declare an array of multiple elements type? For example, we can declare an array consisting of elements of both string and number types in the following way.

const anArrayOfMultipleTypes: (number | string)[] = [1, 'a', 2, 'b', 3, 'c'];

// or
const anArrayOfMultipleTypes: Array<number | string> = [1, 'a', 2, 'b', 3, 'c'];

number | string syntax is called union types. We’ll discuss about this in later posts.

Any

The type any is particularly helpful while working with the 3rd party libraries whose types we might not know. It enables us to avoid compile-time type checking. Try to avoid it as much as possible because it removes the benefits of type checking.

let anUnknownType: any = 'a';

anUnknownType = 10; // TypeScript does not complain!

I’ve found that the above basic types are enough to get started with. There are more mechanisms to declare types that I’ll cover in future posts.

Share on

Get the latest post in your inbox!