Get started with types in Typescript.

Photo by Amy Hirschi on Unsplash

Get started with types in Typescript.

Start using typescript in your projects, save yourself from the runtime errors!

Data types in typescript.

Introduction

TypeScript knows the JavaScript language and will assign data type for you in default cases when you don't add any type. For example in creating a variable and assigning it to a particular value, TypeScript will use the value as its type.

let myName = 'Rakshit';

The code above will create a variable myName and stores a string Raj in that variable. If you try to assign a number into myName, that'll give you error because you cannot store value of any other data type inside it, the type of the value you store initially while declaring the variable cannot be changed.

Declaring variables with required type.

Since typescript is a strongly typed language, you can tell the typescript compiler the data type of the value that you want to be stored inside a particular variable.

Primitive data types.

To declare primitive data types you just have to add : dataType after the variable name.

const userName: string = 'Rakshit';
const isThisFun: boolean = true;
const age: number = 20;

Again, since typescript is strongly typed, you are not allowed to mutate the value of a variable to a different type. For example:

let age: number = 20;
age = '20'; // This is wrong and will give you an error.

Now the question arises that what if you want your variable to be able to store multiple type of values, how will you do that? Simple! Typescript has got you covered! You need to use | whenever you want a variable that can store multiple data types while declaring the types.

let age: number | string;
age = 20; // Right.
age = '20'; // Right.
age = true; // WRONG.

You can also chain the types you want by using | between type names as follows:

let mixed: number | string | boolean;
mixed = true;
mixed = 'You can do this!';
mixed = 100;

As you can see, it kinda just works like the OR operator, so looking at the above example again, if the assigned value is number, string or boolean, then you can assign it to the mixed type, otherwise it'll throw an error.

Arrays

To declare array you just need to add : dataType[] after the variable name.

const hobbies: string[] = ['Playing guitar', 'Coding']; // String array.
const petAge: number[] = [2, 1]; // Number array.

Please note that you cannot mutate the value of the array that is declared by any particular type to a different type and that applies for all elements. For example:

const hobbies: string[] = ['Playing guitar', 'Coding'];
hobbies.push('Working out'); // Right
hobbies.push(20); // WRONG.

You cannot mutate the data type of elements in the array, hence pushing 18 which is a number, will give you an error.

Again, you can use | operator to store multiple types in an array, but you need to put the types inside brackets.

const mixedArray: (string | number | boolean)[] = [20, 'Guitar', false];

Objects

There isn't much difference between javascript objects and typescript arrays except for the strict typing.

const person = {
  name: 'Rakshit',
  age: 20,
  hobbies: ['Playing guitar', 'Coding'],
};

You can declare an object with the properties of required type like this:

let person: {
  name: string;
  age: number;
  hobbies: string[];
};

person = {
  name: 'Rakshit',
  age: 20,
  hobbies: ['Playing guitar', 'Coding'],
};

You cannot add more properties to the objects in typescript.

let person = {
  name: 'Rakshit',
  age: 20,
  hobbies: ['Playing guitar', 'Coding'],
};

person.isAbove18 = true; // WRONG, cannot add new properties.

Dynamic type.

Okay, enough of the strict typing, what if you don't know the type of variable that you might store on your variable? Simple! Typescript got you covered again! ": any" is the data type that lets you store any kind of values in your variable.

let age: any = 20;
age = '20';
let array: any = [18, 20, '18', true, ['Rakshit']];

Functions in Typescript.

You can declare functions in typescript as the same way you did with declaring functions in javascript, i.e Either named functions or anonymous function.

Just a quick recap of functions in JS:

// Named function
function add(x, y) {
  return x + y;
}

// Anonymous function
let myAdd = function (x, y) {
  return x + y;
};

You can also use arrow functions.

Adding typing to the functions.

In addition to that, typescript provides you with a "Function" type that you can declare your variables with and then you won't be able to assign anything other than a function to that variable (Though I don't really think you're gonna use it much that way)

let add: Function;
add = (x: number, y: number) => x + y;

OR

const add = (x: number, y: number) => x + y;

If we try to call the above and we only pass 1 parameter, then the typescript compiler will throw an error because you need to pass at exact 2 parameters. (Yeah, typescript is strict lol).

Please note that you need to also specify the data type of the parameters you want to receive. You can use the | operator here too, when specifying the type of the parameter variable.

Optional parameter

What if you want an optional parameter, which you may or may not want to pass while calling your function? You just need to add ?: [dataType] when defining the function parameters. Eg:

const add = (x: number, y: number, c?: number) => x + y;

This way you are not forced by the typescript compiler to send all of the parameters. Also, always have the optional parameter as the last parameter of the function.

Note: When you are using the default value for the optional parameter, then you don't need to use "?".

Writing the function type.

In typescript you can expand the Function type according to your needs in the following way:

let add: (x: number, y: number) => number;
add = (valueX: number, valueY: number) => valueX + valueY;
add(10, 20);

Here you can only assign the add variable to a function that only accepts 2 parameters that are of number type and that function should only return a value of type number. If the function doesn’t return a value, you would use void instead of leaving it off (while declaring).

A function’s type has the same two parts: the type of the arguments and the return type. When writing out the whole function type, both parts are required.

Also the name of parameters while declaring doesn't really matter, the function will be valid as long as it satisfies the parameter types. Like in the above example, x and y are dummy, they're normally just used for better readability.

To set the return type while declaring and initializing you just need to add : dataType after the parameters. For eg:

const add = (x: number, y: number): number => x + y;

Wrap up!

Great job following so far, the types explained above are some of the types that you will normally use. For more detailed information on all that good stuff, you can visit the official typescript docs!

Feel free to correct me, a feedback would be really great, Thanks!