Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Class and Object in typescript

Someone could explain me what is the difference between class and object in typescript.

class greeter{
  Name: string;
  Sayhello(){
    console.log("hello")
  }
}

Before I using this

var greeter = {
    Name : "",
    Sayhello: function sayhello(){
        console.log("hello");
    }
}
like image 990
Jota Rodríguez Avatar asked Aug 30 '26 05:08

Jota Rodríguez


2 Answers

It is up to you. Both of these are valid and idiomatic TypeScript:

export class Greeter {

    name: '';

    sayHello() {
        console.log('hello');
    }
}

and

export const greeter = {

    name : '',

    sayHello: () => {
        console.log('hello');
    }
}

// if you need just the type of greeter for some reason
export type Greeter = typof greeter; 

If you don't have a need for the class, don't use them.

But you may find benefits of classes if you want to:

  • manage your dependencies with Dependency Injection
  • use multiple instances
  • use polymorphism

If you have multiple instances, using classes or prototype constructor functions, allow you to share method implementations across all instances.

Even if you are in a purely functional paradigm, using prototype constructor functions or classes can be useful for creating monads.

If you only have one instance, and do not need for a constructor, an object is is probably fine.

like image 58
Martin Avatar answered Sep 01 '26 18:09

Martin


There are many differences. On a basic level, a class is an object that can be used to create other objects with a specific shape and functionality. It provides syntactic sugar for functionality that would be a lot more work to accomplish with plain objects and functions.

You should take some time to read about what classes are in the TypeScript Handbook because answering your question in detail would be equivalent to writing a few chapters of a book—especially when tailoring it for TypeScript.

like image 45
David Sherret Avatar answered Sep 01 '26 18:09

David Sherret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!