DEV Community

Audrey Kadjar
Audrey Kadjar

Posted on

🛠️📚 Classes with TypeScript - a cheat sheet

TypeScript enhances JavaScript classes by providing additional features that make it easier to enforce contracts and catch errors at compile time. It's important to note that these TypeScript-specific features are removed at compile time, resulting in standard JavaScript classes.

Here is a cheat sheet summarizing these additional features. You can play with the examples below in this TypeScript playground.


1 - Access modifiers

TypeScript introduced access modifiers for better control over class properties and methods.

  • public: used for properties that can be accessed inside the class, from instances of the class, and outside the class. By default, all class members are public in TypeScript if no access modifier is specified.
  • protected: used for properties that can only be accessed within the class and by subclasses, but not from outside instances of the class.
  • private: used for properties that can only be accessed within the class where they are defined and not by subclasses.
class Counter {
    public count: number;
    protected maxCount: number;
    private hasBeenResetCount: number;

    constructor(maxCount: number){
        this.count = 0
        this.maxCount = maxCount
        this.hasBeenResetCount = 0
    }

    increment():string | number {
        if(this.count === this.maxCount) return "Error: cannot increment passed maxCount"
        this.count+=1
        return this.count
    }

    decrement(){
        this.count--
    }

    reset(){
        this.count = 0
        this.hasBeenResetCount++
    }
}

const myCounter = new Counter(5)
myCounter.increment()
const count = myCounter.count

//Property 'maxCount' is protected and only accessible within class 'Counter' and its subclasses.
//myCounter.maxCount --> ERROR

//Property 'hasBeenResetCount' is private and only accessible within class 'Counter'.(2341)
//myCounter.hasBeenResetCount --> ERROR
Enter fullscreen mode Exit fullscreen mode

2 - Parameter properties

TypeScript provides a shorthand for automatically declaring and initializing class properties in the constructor, which JavaScript does not have. Note that you have to use access modifiers to explicitly declare the parameters in the constructor as class properties; otherwise, you will get an error.

class Person {
    constructor(public name: string, public age: number){}
}

const person = new Person("Audrey", 30);
console.log(person.name); // "Audrey"
console.log(person.age);  // 30
Enter fullscreen mode Exit fullscreen mode

3 - Creating contracts between classes and interfaces

TypeScript allows you to use interfaces to define contracts for classes. Interfaces promote loose coupling by separating the contract (interface) from its implementation (class). Implementing an interface doesn't provide any code to the class (unlike inheritance between classes); it only ensures that the class conforms to the contract, meaning the required methods and properties must be present. A class can implement multiple interfaces, allowing for more flexible design.

interface Shape {
    size: number;
    color: string;
}

interface Metadata {
    createdAt: Date;
}

class Square implements Shape, Metadata {
    size: number;
    color: string;
    createdAt: Date;

    constructor(size: number, color: string, createdAt: Date){
        this.size = size;
        this.color = color;
        this.createdAt = createdAt;
    }
}
Enter fullscreen mode Exit fullscreen mode

4 - The abstract keyword

TypeScript allows you to define abstract classes and methods, providing a way to enforce a structure similar to interfaces but with additional functionality.

  • Abstract classes serve as blueprints for other classes. They cannot be instantiated directly (you cannot create an object of an abstract class).

  • An abstract method is a method defined in an abstract class without a body (implementation). It forces any derived class to implement that method. Abstract methods are like placeholders—they define the signature of the method but leave the implementation details to the subclasses.

abstract class Product {
    abstract getPrice():number;
    abstract getDescription(): string;

    //concrete method 
    getStore(){
        return 'My store'
    }
}

class RedDress extends Product {

    //inherits method getStore
   //implements abstract methods 

    getPrice(){
        return 40
    }

    getDescription(){
        return 'Red dress for cocktail parties'
    }
}


const myRedDress = new RedDress();
myRedDress.getStore() //"My store" 
myRedDress.getPrice() // 40 
myRedDress.getDescription() //"Red dress for cocktail parties" 
Enter fullscreen mode Exit fullscreen mode

I hope this was helpful!

Feel free to reach out if you have any questions! You can also find me on Github, LinkedIn, and Instagram.

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Audrey Kadjar,
Thanks for sharing.