DEV Community

Cover image for How to create a class in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to create a class in TypeScript?

Originally posted here!

To create a class, you can use the keyword class followed by using the {} symbol (opening and closing curly brackets) in TypeScript.

For example, let's say we need to make a class called Person with 2 fields like name and age.

It can be done like this,

// a simple class with 2 fields
class Person {
  name: string;
  age: number;
}
Enter fullscreen mode Exit fullscreen mode

Now to make an instance of the above Person class, we can use the new keyword followed by invoking the Person class using the () symbol (brackets).

It can be done like this,

// a simple class with 2 fields
class Person {
  name: string;
  age: number;
}

// make an instance of the `Person` class
const person = new Person();
Enter fullscreen mode Exit fullscreen mode

See the above code live in codesandbox.

Feel free to share if you found this useful 😃.


Top comments (0)