This tutorial will guide you on how to create classes and objects in TypeScript. TypeScript, a statically typed superset of JavaScript, introduces the concept of types and classes, making it easier to structure your code in an object-oriented manner.
By the end of this tutorial, you will be able to:
Prerequisites: Basic understanding of JavaScript and TypeScript syntax would be helpful, but not necessary as we will cover the basics.
In TypeScript, a class is defined using the keyword class
followed by the name of the class. The class name is typically capitalized.
class MyClass { }
Inside the class, you can define properties (variables associated with the class). These properties will hold the state of the objects.
class MyClass {
property1: string;
property2: number;
}
Methods (functions associated with the class) can be defined inside the class. These methods can access the class properties and perform actions.
class MyClass {
property1: string;
property2: number;
myMethod() {
// actions here
}
}
You can create an object (instance of a class) using the new
keyword followed by the class name and parentheses.
let myObject = new MyClass();
Here are some examples of classes and objects in TypeScript.
Let's create a Person
class with properties name
and age
, and a method introduce
.
class Person {
name: string;
age: number;
introduce() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let bob = new Person();
bob.name = "Bob";
bob.age = 25;
bob.introduce(); // Outputs: "Hello, my name is Bob and I am 25 years old."
Let's add a constructor to our Person
class. The constructor is a special method that is called when an object is created.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let alice = new Person("Alice", 30);
alice.introduce(); // Outputs: "Hello, my name is Alice and I am 30 years old."
In this tutorial, you learned how to define a class in TypeScript, create objects from the class, and define properties and methods for the class. You also saw how to use a constructor to initialize the properties.
Next, you could learn about inheritance and interfaces in TypeScript, which will allow you to create more complex class structures.
Additional resources:
- TypeScript Handbook - Classes
- TypeScript for Beginners - Classes
Create a Car
class with properties brand
, model
, and year
. Add a method displayCarInfo
that outputs the car's information.
Enhance the Car
class by adding a constructor that initializes the brand
, model
, and year
properties.
Create a Student
class with properties name
, age
, and grade
. Add a method promote
that increases the grade by one.
Solutions and explanations will be provided upon request.