The Ultimate Guide to TypeScript: How to Go From Beginner to Pro?

The Ultimate Guide to TypeScript: How to Go From Beginner to Pro?

Published 8th, November, 2022

5 min read

Advanced TypeScript Features, Every Programmer Worth His Salt Should Know. If you’ve already switched to TypeScript, you better not miss these great features too!

TypeScript is a superset of JavaScript. Over the years, after working with JS, developers finally got their deliverance when Microsoft came out with TypeScript, which has made JavaScripting fun!

For example, unlike JavaScript, TypeScript implements static typing, which finds errors with the type of the variable beforehand rather than at the runtime. Also, being a compiled language rather than an interpreted one, helps debug the program more rapidly, thus allowing the application to scale up. However, there is more meat in this new language that you should certainly taste when developing your next application.

Table of Content:

  1. What is Exclude in TypeScript?
  2. What is Extract in TypeScript?
  3. What is Record in TypeScript?
  4. What are Method Decorators in TypeScript?
  5. What is Pick in TypeScript?
  6. What is Omit in TypeScript?
  7. References

What is Exclude in TypeScript?

Exclude is like your decision maker in a buffet luncheon; you can lay your hands on what you want to eat by excluding what your tastebuds don’t appreciate. But we won’t facilitate any distraction and go ahead with an example of a car.

interface reliableButOld {
    name: string
    year: number
    mileage: number
    topspeed: number
    safetystandards: boolean
}

interface newAndBetter {
    name: string
    year: number
    mileage: number
    topspeed: number
    safetystandards: boolean
    electronics: boolean
    design: string
}

type onlyTheBest = Exclude<keyof reliableButOld, typeof newAndBetter>

Having created two interfaces of cars, an old model and a new one, gives us desirable features, while some are not needed. You can create another contemporary car model type by excluding some of the features of the old car and retaining the common ones.

reliableButOld” | “newAndBetter

What is Extract in TypeScript?

The Extract feature enables you to extract only the commonly occurring properties from two different interfaces and form a new one that consists only those properties.

interface Person {
    id: number
    Name: string
    Surname: string
}

interface Employee{
    id: number
    Address: string
    Dept: string
}

type PersonEmp = Extract<keyof Person, keyof Employee>

Here, the property Extract property only gets the common keys from both the interfaces and thus creates a third.

This property can be useful in applications where a third interface object is required whose characteristic is based on overlapping qualities of two different interfaces.

id

What is Record in TypeScript?

The Record property enables users to use the data-type of an interface property as a new data-type itself.

Take the below snippet as an example.

interface AssemblyUnit {
    productid: number
    modelname: string
    placeofmanufacture: string
}

let someUnits : Record<number, AssemblyUnit> = {
  0 : {
    productid : 1,
    modelname : "CyclicSlicer",
    placeofmanufacture : "Shenzhen"
  },
  1 : {
    productid : 2,
    modelname : "CB-joint",
    placeofmanufacture : "Pune"
  },
  2 : {
    productid : 3,
    modelname : "SuctionShaft",
    placeofmanufacture : "Hyderabad"
  },
}

In the above example, the Record property has changed the number data-type into a new type called someUnits where every key is a number and its values are AssemblyUnit properties.

The application of this property is, when you want to create a new data-type that is based on the instances of an already existing interface. This is particularly useful when you want to work with specific objects of the original instance, as a combined unit.

What are Method Decorators in TypeScript?

Decorators in general are properties or logical implementations that we attach to classes, functions, or properties. Let’s begin by understanding the most common of them; decorators implemented on methods with the help of decorator factories.

function exercise(activity: string) {
    console.log(“${activity}, is what needs to be done”) 
    
    // decorator factory contains the logic that leads to
    // the decorator being created

    return function (final: Array<string>) {

        final.push(activity)

        console.log(“${activity} has been included in final array”)

        // this is the decorator body
        // do something with 'activity' and 'final'
    };
}

@exercise(activity)
function decisiontoworkout(goahead: boolean) {
	console.log(“Are you gonna workout from today? ${goahead}! ${activity}!”)
}; 

So basically, the decorator function decisiontoworkout was wrapped with the decorator exercise and the result we got was a not only a combined output of exercise and decisiontoworkout, but also the variable activity from the former was used in the later.

“jumps is what needs to be done”
“jumps has been included in the final array”
“Are you gonna workout from today? true! Jumps!”

What is Pick in TypeScript?

You have an assortment of ingredients and veggies for making a Pepperoni, but you’re in a mood to only make a quick snack from bell pepper and cheese, ignoring all others. This is where you picked only what you needed.

Similar is the case with the Pick utility type where you pick only certain properties from an interface to create a new data-type.

interface Vehicle {
    type: string;
    maxspeed: number;
    year: number;
    mileage: number;
    brand: string; 
    origin: string;
}

If I want to create another data-type, let’s say, racers, I’ll select only the properties that I want to describe the data-type racers.

type racers = Pick<Vehicle; “maxspeed” | “mileage” >;

racer_1: racers = {
    maxspeed : 200,
    mileage: 100
};

What is Omit in TypeScript?

This guy is just the reverse of the one above. Instead of picking what you want, you pick what you don’t. So naturally, you’ll be using Omit to weed out the undesirables.

An ideal situation to use this utility type is when you tons of desirables and an unlucky few. Here’s an example.

interface Account {
    type: string;
    id: number;
    name: string;
    balance: number;
    bank: string;
    internationalized?: boolean;
}

type account_unattached = Omit<Account, “name”>;

We excluded bank because accounted_unattached means we are collecting bank accounts independent of the account holder’s name, for say, some sort of a survey.

As you can see, name is a redundant detail which has been omitted during the creation of data-type account_unattached.

For those of you who have also worked on Python extensively, you’ll notice this at the get go that some of these properties are very similar to some Python features. This ‘mutation’ found in TypeScript renders an extra power to its native JavaScript-based beauty, and hence a growing choice for many developers recently.

Although there are few more of these properties, we think that these are the most crucial to understand and also enough for you to start.

To put TypeScript’s advanced features into perspective, consider these as ‘Pythonic features’ being integrated into JavaScript and now you have best of both the languages.

To know more about the world of programming, stay tuned.

Description: Typescript is rapidly rising as a great alternative to JavaScript since it provides all the desired features, along with a ton of new ones of its own. For those who have already worked with TypeScript, their positive experience with the language is a testament to its success. This article goes a notch above and introduces a few but important features from the vast sea of its features. The goal of this article to introduce the thin layer of possibilities to show noobs and old guards that Typescript is more awesome than they thought.

The features mentioned in the article are very relatable, even to those who have come from awesome technologies like Python, and have been explained in an easy manner with precise examples. In fact, even if one has begun with Typescript recently with not a lot to show, they can still implement these in their projects to make things work faster.

Method decorators, omit and pick features are perhaps the most relatable to those who come from a family of modern programming languages. These features don’t need to be supported by complex code but rather simple snippets such as Typescript interfaces. On the other hand record, extract and exclude are follow the same nature of separating the needed from the unneeded as well as creating new data-types.

There are, of course, more features than these, but for starters these are just fine. We plan to eventually cover more advanced features of Typescript to spread its seeds, so that JS fanboys can finally evolve.

References

  1. freecodecamp
  2. educative
  3. typescriptlang