Let’s Learn Typescript | Interfaces and Generic Types (The Typing System) 02

Subscribe to my newsletter and never miss my upcoming articles

Video Tutorial

Overview

One of the main reasons that Typescript does exist in the first place is offering a static typing system to the javascript world which gives you more flexible control over your code base and how the source code should be able to be tied up together in order for better performance and more reliable algorithms and data structures.

You will understand the benefits of it once you use, so if you have been in the javascript wold for a really long time then you will probably won’t get the point behind using a static typing language and why to not only stick with the dynamic typing system that you always loved and worked with over you different project types.

Well, we will discuss the main reasons why a static typing system may save the day for you and your teams.

Most of the big teams who made the great apps we know and we love did move from javascript to complete typescript being used on all of there apps and projects, so massive shoutout to Airbnb team, Microsoft and GitHub for using typescript and making it possible.

Make sure to watch the previous tutorial for getting started guide and setting up the working environment.

We will use Node.js for running the compiled javascript code just for making it easier for the tutorial.

Typescript Types

As any other statically typed language it has it own primitive built-in types that you can use during your development (the base types), typescript also has those types that you can use.

//Base Types 
let me: string = "Hello World!";
let num: number = 50.12568;
let bool: boolean = true;
//As you can see in order to set the type of a variable you use the colon after variable name.
//And you specify the type you want from this variable to be.

The built-in types are string, number, and boolean types but since in the above example we are assigning the variable to its value directly then we can ignore specifying the variable type because typescript is smart enough to know the assigned type and reflect upon it.

Beside the above type that you need the most, there are other data structure and nullable types.

//Array and Object are also types.
let myArr: Array<string> = [];
let myObj: Object = {};
//Quite simple but in this way we can't use it as we need so it is not quite important.

//Null and Undefined are also a types 
let nothing: undefined = undefined;
let empty: null = undefined;
//You may need to set a variable to null or undefined in your code.

Interfaces

Interfaces are the main power of typescript and why you consider using typescript in the near future if you still doubting about it.

Interfaces are a way to declare custom types the same as structs on c/c++ or if you are a Java developer already you should already be familiar interfaces, they allow you to create new custom types to use on your code base using the built-in types or even your other custom types.

//Here is a Pet type
interface Pet {
    name: string;
    color: string;
    fat: boolean;
}
//it is the same as declaring an object.
//I recommend using semi colons

It is so simple to define a new type using the primitive types.

Now you can use this type to define a new object has the same parameters as you set in the type.

//My Littel Pet!
let myPet: Pet = {
    name: "berty",
    color: "white",
    fat: false,
}

You can add whatever attributes to the type so you can use then on your declared object, but without strictly specifying the type you won’t be able to set attributes directly to an object since typescript needs to know about the type so it could create the object.

Let’s say know we have a new pet type and we need to extend it from the base Pet type.

//Extended Type 
let Dog extneds Pet {
    yelp: () => void;
}
//we add a yelp method to the type so the dog will yelp it's name

Extending from a base type basically means that we want to use the base type properties alongside other custom properties that we want to add, in this case, we added a new yelp method to the Dog type which only available in the Dog type, not the Pet.

To define a method type we set the attributes and the return type of the method, the yelp method has no parameters and returns nothing (Void) so all it does is executing something which is yelling the name of the Dog, we only defined the method but still we haven’t specified the method declaration yet.

//New Dog 
let myDog: Dog = {
    name: "Apollo",
    color: "yellow",
    fat: true,
    yelp: function() {
        console.log("Wooahh !", this.name);
    }
}
//As you can see the Dog type still need the Pet properties + it own properites (yelp method)
//We add the method declaration as we would normally do in javascript
/*we use function keyword for declaration instead of ES6 arrow function cause it allows us to access this*/

So we still can use the Pet type properties in the extended Dog type, which is a pretty cool thing that you can use to make your objects talk to each other smoothly.

Now you can use the declared object as you would normally do on normal javascript code, let’s try to call the yelp method on Apollo (The Dog!).

//Call the method
myDog.yelp();
//OUTPUT: Wooahh ! Apollo.

Generic Types

For generic types you can create a generic functions/methods that will take care of common operations among different types, generic basically means any type can be used.

//Generic function (Convert any type to string)
function convertToString<T>(arg: T): string { 
    return String(arg);
}
//we use brackets to specify the generic type after function name and before braces
//the argument it takes is a type of Generic that we have just declared
//And since we convert any type to a string so the function must return a string (: string)

//If you would call the abover function you can use any type you want to convert to a string
let str: string = convertToString(50);
//log it on the console
console.log("To String: ", typeof str);
//We use typeof keyword to check the type of the variable (make sure that is a string!).

Generic types are usually used on functions to do a common job between multiple types that will help you either to speed up the work progress and/or declare an efficient typing system.

What’s Next

Since we have learned how interfaces and the typing system of typescript work alongside generic types and how they should probably used, now you start using typescript even though you still at the beginning of the series but still after learning the typing principles you will be able to use typescript with no problems.

No Comments Yet