How to Create an Object in Typescript ?

TypeScript is an open-source programming language developed and maintained by Microsoft. It serves as a superset of JavaScript, which means that any valid JavaScript code is also valid TypeScript code. It’s mainly designed for large-scale projects. TypeScript comes with extra added features like Static Type Checking, Modularity, Class-Based Objects, Modularity, ES6 Features, and a Syntax similar to High-Level Languages like Java.

Creating Objects in Typescript:

Now, let us see multiple ways in which objects can be created using Typescript

Fundamentally, Javascript runs with Template-based code snippets, we can create objects directly without creating classes, with the help of Object literal and constructor methods. 

1. Object Literals:

Object literals are sets of name-value pairs stored in comma-separated lists.

Syntax:

let Name_of_object = { 
object_property : value,
object_property : value
}

Example to Create Object using Object Literals:

In this example, we will create an object in typescript.

Javascript
let Employee_details = {
    Empname: "John",
    EmpSection: "field"

}
console.log("Employee Name is:" + 
    Employee_details.Empname + 
    " Employee's section is:" 
    + Employee_details.EmpSection
);

Output: 


2. Constructor Method:

Constructor methods are used for initializing objects created within a class. Only one constructor method is allowed per class.

Syntax:

function Name_Of_Constructor( property1, property2, ...) {} 

Inside Constructor:

Inside this Constructor method, we can initiate parameter values to properties of objects using the “this” keyword. 

function Name_Of_Constructor( property1, property2, ...) { 
this.property1 = parameter_value;
this.property2 = parameter_value;
}

or

We can declare both properties of the object and parameter with the same name. 

function Name_Of_Constructor( property1, property2, ...) {
this.property1 = property1;
this.property2 = property2;
}

Explanation:

“this” Keyword references object property with the required parameters, to simply say “this” keyword represents the object to which we are initiating parameters with the help of the constructor method. 

Example to Create Object using Constructor Method:

In this example, we will use the constructor method.

Javascript
function Employee(Employee_fn, Employee_ln, Employee_age) {
   this.fn = Employee_fn;
   this.ln = Employee_ln;
   this.age = Employee_age;
}

var p1 = new Employee("Raviteja", "Velamuri", 24);
console.log("Name: " + p1.fn + " " + p1.ln);
console.log("Age: " + p1.age);

Output: 


3. Passing Objects as Function Parameters:

Objects can be passed as arguments to functions in TypeScript, specifying required object properties within the function definition.

Syntax:

let Name_Of_Object {
property = property.value ;
}
function function_name(
obj : { property_name : property_type }
) : return_type {
obj_param.property
}

Example:

In this example, we will pass an object as a parameter to functions.

Javascript
let employee = {
    firstname: " Raviteja ",
    lastname: " Velamuri ",  
}
function display( obj: { 
    firstname:String,lastname:String
}) : void {  
    console.log("Name is"+obj.firstname+" "+
        "lastname is"+" "+obj.lastname);
}  

display(employee);

Output: 

4) Using Object.create() method:

The Object.create() method creates a new object with the specified prototype object and properties. It allows you to create objects that inherit properties from another object (referred to as the prototype), without calling a constructor function.

Syntax:

let newObj = Object.create(proto[, propertiesObject]);
  • newObj: The newly created object.
  • proto: The object to use as the prototype for the newly created object.
  • propertiesObject (optional): An object whose enumerable own properties specify property descriptors to be added to the newly created object, with the corresponding property names.

Example:

In this example, we will create object using Object.create() method.

JavaScript
let personPrototype = {
    greet() {
        return `Hello, my name is ${this.name}.`;
    }
};

let person = Object.create(personPrototype);
person.name = "Pankaj";
person.age = 20;
person.gender = "male";

console.log(person);
console.log(person.greet());

Output:


5) Using Classes:

Classes in TypeScript provide a syntax for creating objects with predefined properties and methods. They offer a more structured and object-oriented approach to defining object blueprints, encapsulating data, and behavior.

Syntax:

class ClassName {
property1: type1;
property2: type2;
// ...

constructor(param1: type1, param2: type2 /* ... */) {
this.property1 = param1;
this.property2 = param2;
// ...
}
}
  • ClassName: The name of the class.
  • property1, property2, …: Properties of the class.
  • param1, param2, …: Parameters for the class constructor.

Example:

In this example, we will create object using Class.

JavaScript
class Person {
    name: string;
    age: number;
    gender: string;

    constructor(name: string, age: number, gender: string) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    greet() {
        return `Hello, my name is ${this.name}.`;
    }
}

let person = new Person("Pankaj", 20, "male");

console.log(person);
console.log(person.greet()); 

Ouput:

Key Features of TypeScript

  1. Static Typing: Define types for variables, function parameters, and return values.
  2. Interfaces: Shape complex data structures and enforce contracts.
  3. Enums: Improve code readability with named constants.
  4. Decorators: Enhance class properties and methods.
  5. Union Types: Allow values to have multiple types.

Conclusion:

These methods illustrate various approaches to object creation in TypeScript, offering flexibility and efficiency in managing data structures within the codebase.