Let’s Learn Typescript | Work With Classes, Modules and Enums 03

Video Tutorial

Overview

You could pretty much use typescript the same as any other statically typed language (Java, C++) and this is why you should consider using it on your next projects.

Classes are a very interesting data structure that helps deliver great structured code base, while ES6 has introduced classes on javascript but still some missing pieces that typescript compliments by its own, we are also going to see basic (ts/js) modules how to import and export a different piece of your code around your project, so if you are already familiar with ES6 modules system this should be the same with no change.

We will also take a look on Enums and why they are very important to use on a typescript project.

Typescript Classes

Classes are an advanced data structure that will revolutionize the way you think about code, so if you have never used classes before this is your opportunity to dive into it and enjoy leaving in the new world.

We can use interfaces to type classes.

interface ClassInterface {
    name: string;
    age: number;

    sayMyName: () => void;
}
//Use the interface to type the class (the same as regular variable)
class Person implements ClassInterface {
    name: string;
    age: number;

    sayMyName() {
      //Say Something 
    }
}

As you can see when we need to declare a class variable we have to put the declaration under the class scope first, so later we can use on the class methods.

Let’s say we have a grandparent class that has some properties.

//Classes in Typescript 
class GrandParent {
    //PRIVATE/PROTECTED PROPERTIES
    protected name: string;
    //Public Property
    public available: string;

    constructor() {
        //Called first when creating class instance 
        this.name = "Albert";
        console.log(`Grand Parent, ${this.name} Initialized!`);
    }

    setName(newName: string) {
        this.name = newName;
    }

    getName() {
        return this.name;
    }
}

In classes, you can also specify the type of the property, either public, private or protected public basically means that this property can be access outside of the class scope so you can change this property or get its value, private is only available under the class scope so when you create an instance of the class you can’t use that instance to access a private class property.

where protected simply allow you to use it as a private on the current class scope and children of this class can also access the protected property.

The constructor method on a class is the initialization method which gets called first whenever you create a class instance.

Now let’s create a child class that inherits from the grandparent class (base).

class Parent extends GrandParent {
    protected age: number;
    constructor(name: string) {
        super(); ///< Make sure it is called first!
        this.name = name;
        this.age = 56;
    }
    set setAge(newAge: number) {
        this.age = newAge;
    }
    get getAge() {
        return this.age;
    }
}

To create a child class from a base (grandParent) we simply declare a normal class but we use the extends keyword to specify which class we are going to inherit from (base).

On a child class which extends from a base class Under the constructor, we have to class the super method so we need to initiate the base class whenever we are creating an instance of the child class.

If you can notice in the constructor we can easily access the name property which part of the grandparent class the class we are extending from, and that is because we set it to protected and that is one of the power points of inheritance.

To create an instance.

//Use the new keyword to create and instance of the class 
let Eduard = new Parent("Eduard");
//We use the getters to get name and age
console.log("Parent Name: ", Eduard.getName(), " Age: ", Eduard.getAge);
//We use getter cause we can directlly access the name property (remember it is protected) so we do a workaround by creating a class method that can return the name or the age.

Also, There are other types that you can use on a class property, readonly which allows a property to be readonly and can not change on runtime and static properties which basically are independent of the class instance.

class MyClass {
   readonly gravity = 9.8;
   static famillyName = "einstein";
}
//Create an instance 
let instance = new MyClass();
//We can get the value of the gravity (readonly) but we cannot change it.
console.log("Gravity: ", instance.gravity);
//For Static we can't access it through the instance, we need the class object
console.log("Familly: ", MyClass.famillyName);
//Static variables are shared accross all instances

Typescript Modules

//Modules are identical between javascript and typescript
//Module1
let myObj: any = {name: "Eduard"};
//To export it (let other modules import it)
export myObj;
//Or for a class 
export class SharedClass {
...
}

Now from the other modules you can access and import the code pieces that you did export.

//Main Module
//The modules are in the same directoy so use relative path to import from modules 
import { myObj, SharedClass } from "./module";
//Now you have the right to access myObj and sharedClass

If you are already familiar with ES6 import/export system it is identical for typescript.

Typescript Enums

Enums are a special data structure, may help you a lot in some state case scenarios.

//Let say that you want to create a state object
Enum States = { ACTIVE, DISABLED, ONGOING };
//Then you can access the num properties (states)
let currentState = 0; ///< 0 refres to ACTIVE since enum starts from 0 indexing
//ACTIVE = 0, DISABLED = 1, ONGOING = 2;
if(currentState = States.ACTIVE) //Do something Fun!

//You can also use string to represent enum values instead of number
Enum States = { ACTIVE = "ACTIVE", DIABLED = "DISABLED", ONGOING = "ONGOING" };
//Enum should have the same data type.

Enums are a quite interesting data type alongside it is super simple to deal with, make sure to check the official docs for further info.

What’s Next

Typescript opens brand new opportunities for you to explore and learn where classes are a very important data type alongside modules manipulation and state enums.

You still may need to read more about an advanced topic on the Offical typescript’s Docs.

No Comments Yet