Typescript - Object Type and Object with examples

In this blog post, We are going to learn the typescript object type with examples.

Typescript - Object Type and Object with examples

In the typescript, the object has three variations of creating objects.

1. Object
2. object
3. {}

Typescript object type 

Typescript introduced a new data type called object type. this object represents types which are not primitive types like string, number, void, boolean, null and defined.

The reason to introduce to other object type is as follows

Below Javascript Object class has methods which take an object as a parameter. In Typescript, there is non-primitive type representation for this methods. object type is introduced.




passing primitive values to the above methods throws at runtime. Typescript gives compilation error because of the object type assertion check

object declaration

const obj: object = {};  

Object Class 

This is Object class which is core Superclass for all javascript API classes which contain methods toString and toLocalString

Empty Object -

This is a custom object which has an empty object with no variables and methods. Empty Object and Object point to the same type

let myobject = {};  
myobject.key = 'test';  

In the empty object, there is no key associated, It gives compilation error - Property key does not exist on type{} Object also can be created using predefined properties Here created object of Emp with two properties name and id of type string and number Typescript treat this object as {name:string,id: number} when you assign any values other than of different types, It gives compilation error


var Emp = {  
  name: 'Tom',  
  id: 1  
Emp = {  
  name: 'Kiran',  
  salary: 2000  

In the below example, Created object, and now changing object with different values as well as modifying object structure, This gives compilation error as a new object is not assignable to an existing object
The object can be used in many ways like below thing

  • The object contains functions including properties¬†
  • Can be created using object literals¬†
  • Can be passed an object to a function¬†
  • Can also object verified using duck typing means if the two objects contain 1. Same type 2. Same properties

How to check if two objects type equality?

Typescript Reflection API provides a constructor to check object type and returns ClassName Here is an example of checking objects of the same type.

class Parent {}  
class Child extends Parent {}  
var parent = new Parent();  
var child = new Child();  
var parent1: Parent;  
parent1 = new Child();  
console.log(parent.constructor == Parent); // returns true   
console.log(child.constructor == Child); // returns true  
console.log(parent1.constructor == Child); // returns true  
console.log(parent1.constructor == Parent); // returns false  

Similar Posts