In TypeScript, creating objects can be done in several ways, with the most common being the use of classes (class) and interfaces (interface). Below are the basic syntax and examples for both methods.
1. Using Classes (Class)
In TypeScript, classes are implemented as part of ES6 standards and also include additional features such as type annotations, constructors, and inheritance. The basic steps to create an object are to define a class and then use the new keyword to instantiate an instance of the class.
Syntax Example:
typescriptclass Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } describe(): string { return `My name is ${this.name} and I am ${this.age} years old.`; } } // Create object const person = new Person("John", 30); console.log(person.describe());
2. Using Interfaces (Interface)
Interfaces in TypeScript are primarily used to define the type of objects. They are not a direct method for creating objects but rather define a specification that objects must adhere to. When creating objects, you must ensure that the object conforms to the interface's structure.
Syntax Example:
typescriptinterface IPerson { name: string; age: number; describe(): string; } // Create object const person: IPerson = { name: "Alice", age: 25, describe: function() { return `My name is ${this.name} and I am ${this.age} years old.`; } }; console.log(person.describe());
Example Explanation
In the first example, we define a class named Person that has two properties (name and age) and one method (describe). We create an instance of the Person class using new Person("John", 30) and call its describe method to retrieve the description.
In the second example, we define an interface named IPerson to specify that an object must include the properties name, age, and the method describe. Then we create an actual object person that conforms to the IPerson interface structure and implements the describe method.
Both methods are very common in TypeScript. Classes enable more complex object-oriented programming, while interfaces are a powerful tool for ensuring type safety.