[Angular / TypeScript] Constructor Assignment in various ways

Eden Park
2 min readMay 29, 2022

Microsoft introduced TypeScript in 2012 enabling us to code JavaScript in a object-oriented fashion. It is sometimes necessary to have a constructor in a class to have a certain logic for specific properties. In this article, we are discovering ways of creating an object using a constructor. The full example can be access from [StackBlitz].

Parameterized Constructor

Parameterized Constructor

You can create an object as below

const employee = new EmployeeOne(1, "Name");

Shorter Version of Parameterized Constructor

Shorter Version of Parameterized Constructor

You can create an object as below

const employee = new EmployeeTwo(1, "Name");

Object as a parameter

Object as a parameter

You can create an object as below

const employee = new EmployeeThree(1, "Name");

Object.assign(this, params)

Object.assign(this, params)

You can create an object as below

const employeeThree = new EmployeeFour({ code: 1, name: ‘Three’ });

Partial<Class>

Partial utility is designed to make all of the properties of a type optional.

Partial<Class>

You can create an object as below

const employeeFive = new EmployeeFive({ code: 1, name: 'Five' });

With Empty Object initialization

With Empty Object initialization

You can create an object as below

const  employeeSix = new EmployeeSix({ code: 1, name: 'six' });

Summary

We have seen many ways to creating an object using a constructor. We can modify the right hand side to add more logic for the property that you want to change. Happy Coding 😄

--

--