Logo

dev-resources.site

for different kinds of informations.

πŸ› οΈπŸ“š Classes with TypeScript - a cheat sheet

Published at
10/16/2024
Categories
javascript
webdev
typescript
ts
Author
audreyk
Categories
4 categories in total
javascript
open
webdev
open
typescript
open
ts
open
Author
7 person written this
audreyk
open
πŸ› οΈπŸ“š 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.

ts Article's
30 articles in total
Favicon
How to improve the Frontend part of the project using one button as an example :))))
Favicon
Azure App Service doesn't returned compressed (gzip) files for Angular application?
Favicon
Deploying a Simple Static Website on AWS with CDK and TypeScript
Favicon
Understanding Next.js and TypeScript Tutorial
Favicon
πŸ› οΈπŸ“š Classes with TypeScript - a cheat sheet
Favicon
Event Loop in 2 Minutes
Favicon
How Boring It Is to Write Articles or Talk to Certain Types of Developers These Days.
Favicon
How ts-pattern can improve your code readability?
Favicon
isNaN vs Number.isNaN
Favicon
πŸ› οΈ πŸ“¦ TypeScript Generics - a cheat sheet
Favicon
TypeScript Generics: How to Write Flexible and Type-Safe Code
Favicon
Introduction to TypeScript
Favicon
Dominando os Utility Types do TypeScript
Favicon
Nega aynan Vue.js ?
Favicon
TS-BoilerplateX
Favicon
What Are Standalone Components Angular 17 ?
Favicon
Navigating the JS TS Limbo
Favicon
Demystifying TypeScript Generics with Simple Examples
Favicon
Typescript enum vs. "as const"
Favicon
Mastering TypeScript: A Comprehensive Tutorial
Favicon
m3u8 to mp4 with merged audio
Favicon
Shouldn't an NPM package that helps hundreds of thousands of programmers increase their productivity tenfold be open-sourced?
Favicon
ChatGPT: how I used it to convert HTTP requests to OpenAPI document
Favicon
Cleaning up unused Typescript Files with `ts-prune`
Favicon
Intern's Guide Chat GPT Full Stack: Nest, React, Typescript
Favicon
Using LiteFS with Bun on Fly.io
Favicon
Know your users' location in React Ts
Favicon
Regex #1: Understanding Regex, Regex-Based String Methods and Regex Flags
Favicon
The Witcher Card Game Live
Favicon
Powerful File System manager for Nodejs

Featured ones: