20 Feb 2024
In TypeScript, which is a superset of JavaScript, you have several ways to create objects, similar to JavaScript. TypeScript adds static typing and other features that enhance object-oriented programming. Here are the common ways to create objects in TypeScript:
-
Object Literal: TypeScript supports object literals, just like JavaScript. You can define objects with key-value pairs enclosed in curly braces
{}.let person = { name: 'John', age: 25, occupation: 'Developer' }; -
Class: TypeScript supports classes, which are blueprints for creating objects. You can define a class with properties and methods.
class Person { name: string; age: number; occupation: string; constructor(name: string, age: number, occupation: string) { this.name = name; this.age = age; this.occupation = occupation; } greet() { console.log('Hello!'); } } let person = new Person('John', 25, 'Developer'); -
Interface: TypeScript allows you to define interfaces that describe the structure of objects. Interfaces are used for type-checking and can define object shapes without implementing any functionality.
interface Person { name: string; age: number; occupation: string; } let person: Person = { name: 'John', age: 25, occupation: 'Developer' }; -
Factory Function: TypeScript supports factory functions, just like JavaScript. Factory functions are functions that return objects.
function createPerson(name: string, age: number, occupation: string): Person { return { name: name, age: age, occupation: occupation }; } let person = createPerson('John', 25, 'Developer'); -
Object.create(): TypeScript also supports
Object.create(), which allows you to create a new object with a specified prototype object.let personPrototype = { greet: function() { console.log('Hello!'); } }; let person = Object.create(personPrototype); person.name = 'John'; person.age = 25;
These are some common ways to create objects in TypeScript. Choose the method that best suits your needs based on your project requirements and coding style.