Typescript - Object Type and Object with examples
- Admin
- Dec 3, 2023
- Typescript
In this blog post, We are going to learn the typescript object type with examples.
In the typescript, the object has three variations of creating objects.
- Object
- object
- empty braces
You can check another post on Fix for Object is possibly null
Typescript object type
Typescript introduced a new data type called object type. this object represents types that are not primitive types like string, number, void, boolean, null, and defined.
The reason to introduce other object types is as follows
Below Javascript Object class has methods that take an object as a parameter. In Typescript, there is a non-primitive type representation for this method. object type is introduced.
- Object.getOwnPropertyDescriptor
- Object.create
- Object.observe
passing primitive values to the above methods throws at runtime. Typescript gives a compilation error because of the object type assertion check
object declaration
const obj: object = {};
Typescript Object Class
This is an Object class which is the core Superclass for all javascript API classes which contain methods toString and toLocalString
Typescript Empty Object create empty braces
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 a 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 a compilation error
typescript object Examples
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 the below thing
- The object contains functions including properties
- Can be created using object literal
- 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 in typescript?
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