TypeScript Classes and Objects
Are you ready to take your TypeScript skills to the next level? If so, then you need to learn about TypeScript classes and objects! These powerful tools will help you create more complex and dynamic applications that can handle a wide range of tasks.
In this article, we'll explore TypeScript classes and objects in depth, covering everything from the basics to advanced techniques. By the end, you'll have a solid understanding of how to use these tools to build robust and scalable applications.
What are TypeScript Classes?
At its core, TypeScript is a superset of JavaScript that adds support for static typing and other advanced features. One of the key features of TypeScript is its support for classes, which are a fundamental building block of object-oriented programming.
A class is a blueprint for creating objects that share common properties and methods. In TypeScript, you can define a class using the class
keyword, followed by the name of the class and a set of curly braces that contain the class's properties and methods.
For example, here's a simple TypeScript class that defines a person:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
In this example, we define a Person
class that has two properties (name
and age
) and one method (sayHello
). We also define a constructor method that takes two parameters (name
and age
) and assigns them to the corresponding properties.
Creating Objects from Classes
Once you've defined a class, you can create objects from it using the new
keyword. For example, here's how you could create a new Person
object:
const person = new Person('Alice', 30);
In this example, we create a new Person
object with the name "Alice" and the age 30. We can then call the sayHello
method on this object to print out a greeting:
person.sayHello(); // Output: "Hello, my name is Alice and I'm 30 years old."
Access Modifiers
One of the key benefits of using classes in TypeScript is that you can use access modifiers to control how properties and methods are accessed. TypeScript supports three access modifiers: public
, private
, and protected
.
A public
property or method can be accessed from anywhere, both inside and outside the class. This is the default access modifier if you don't specify one explicitly.
A private
property or method can only be accessed from within the class itself. This means that other code outside the class cannot access or modify the property or method.
A protected
property or method can be accessed from within the class itself and any subclasses that inherit from it. This means that other code outside the class cannot access or modify the property or method, but subclasses can.
Here's an example that demonstrates how access modifiers work:
class Person {
public name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public sayHello() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
class Employee extends Person {
private salary: number;
constructor(name: string, age: number, salary: number) {
super(name, age);
this.salary = salary;
}
public getSalary() {
return this.salary;
}
}
const person = new Person('Alice', 30);
person.name = 'Bob'; // OK
person.age = 40; // Error: Property 'age' is private and only accessible within class 'Person'.
const employee = new Employee('Charlie', 35, 50000);
employee.name = 'David'; // OK
employee.age = 45; // Error: Property 'age' is private and only accessible within class 'Person'.
employee.salary = 60000; // OK
In this example, we define a Person
class with a public
name
property and a private
age
property. We also define a sayHello
method that prints out a greeting.
We then define an Employee
class that extends the Person
class and adds a private
salary
property and a getSalary
method.
Finally, we create a Person
object and try to modify its name
and age
properties, which works for name
but not for age
because it's private
. We also create an Employee
object and try to modify its name
, age
, and salary
properties, which works for name
and salary
but not for age
because it's private
.
Static Properties and Methods
In addition to instance properties and methods, TypeScript also supports static properties and methods. A static property or method belongs to the class itself, rather than to any individual object created from the class.
To define a static property or method, you use the static
keyword. Here's an example that demonstrates how static properties and methods work:
class Person {
static count: number = 0;
constructor() {
Person.count++;
}
static getCount() {
return Person.count;
}
}
const person1 = new Person();
const person2 = new Person();
const person3 = new Person();
console.log(Person.getCount()); // Output: 3
In this example, we define a Person
class with a static
count
property that keeps track of how many Person
objects have been created. We also define a static
getCount
method that returns the current count.
We then create three Person
objects and call the getCount
method to print out the current count, which is 3.
Conclusion
In this article, we've covered the basics of TypeScript classes and objects, including how to define classes, create objects from them, use access modifiers to control access to properties and methods, and define static properties and methods.
By mastering these concepts, you'll be well on your way to building more complex and dynamic applications with TypeScript. So what are you waiting for? Start experimenting with TypeScript classes and objects today!
Editor Recommended Sites
AI and Tech NewsBest Online AI Courses
Classic Writing Analysis
Tears of the Kingdom Roleplay
Learn Postgres: Postgresql cloud management, tutorials, SQL tutorials, migration guides, load balancing and performance guides
Share knowledge App: Curated knowledge sharing for large language models and chatGPT, multi-modal combinations, model merging
Developer Key Takeaways: Key takeaways from the best books, lectures, youtube videos and deep dives
Build Quiz - Dev Flashcards & Dev Memorization: Learn a programming language, framework, or study for the next Cloud Certification
Rust Language: Rust programming language Apps, Web Assembly Apps