TypeScript Unlocked: Type Aliases

TypeScript Unlocked: Type Aliases

·

2 min read

💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.

Type Aliases allows us to define the structure or shape of the object with the help of type keyword. Lets understand this with an example.

function add({num1, num2}: {num1: number, num2: number}): number  {
    return num1 + num2
}

function sub({num1, num2}: {num1: number, num2: number}): number  {
    return num1 - num2
}

let sum = add({num1: 2, num2: 3})
let diff = sub({num1: 3, num2: 2})
console.log(sum, diff);

In this code we define two functions, add and sub. Both the function accept the same type of object. So we need to define the same structure of object at two different places. Now if i want to add the functions to multiply and subtract I have to define the same thing again.

Type Aliases solves this problem. using type keyword we can define the structure or shape of the object only once and than use that type everywhere else.

type Nums = {num1: number, num2: number}

function add({num1, num2}: Nums): number {
    return num1 + num2
}

function sub({num1, num2}: Nums): number  {
    return num1 - num2
}

function mult({num1, num2}: Nums): number {
    return num1 * num2

}

function div({num1, num2}: Nums): number  {
    return num1 / num2
}

let sum = add({num1: 2, num2: 3})
let diff = sub({num1: 3, num2: 2})
let prod = mult({num1: 10, num2: 2})
let quot = div({num1: 10, num2: 2})
console.log(sum, diff, prod, quot)

Type Aliases make the code much cleaner and easier to maintain. There is also something called interface which is similar to type. We will discuss about interfaces and how they are different from types as we go ahead with this series.

if you reached till here and you liked what you read don't forget to like and share it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding TypeScript to it. Happy coding!

Â