Close
Close full mode
logoWebDevAssist

Introduction to object type in TypeScript

TypeScript object type introduction:

Object type is a special type for TypeScript. We can use this type with objects. In this post, we will learn how to use Object type with different examples.

YouTube video:

I have published one video on the Object type. You can watch it here:

Why object type is required:

Let's consider the below program:

const printData = (data: any) => {
console.log(data);
};
printData("hello");
printData({ id: 123, name: "Alex" });

We have one method printData that takes one argument data of any type. It uses a console.log to print the data. This method is called with a string and with an object. It will print:

hello
{ id: 123, name: 'Alex' }

As the type of data is any, it will work with any type of data. We can create object types for these type of items.

Object type:

We can create an object type simply as below:

const printData = (data: {id: number, name: string}) => {
console.log(data);
};
printData({ id: 123, name: "Alex" });

It will throw one error for any other different type of object.

Define the type in a separate variable:

It is a good practice to define the type in a separate variable. We can use the type instead of defining the object type in all the places where it is used.

type dataType = {id: number, name: string};
const printData = (data: dataType) => {
console.log(data);
};
printData({ id: 123, name: "Alex" });

We created a type dataType that is used as the type of the parameter for printData.

Object type with complex objects:

Object type is useful with complex objects. For example,

type dataType = {id: number, name: string, info: {type: string, color: string}};
const printData = (data: dataType) => {
console.log(data);
console.log(`Color: ${data.info.color);
};
printData({ id: 123, name: "BMW", info: {type: "Car", color: 'Red'} });

The dataType represents a complex object. It will show an error if we call printData with a different object. We can also use optional parameters in the object.

Subscribe to our Newsletter

Previous
Introduction to union type in TypeScript
Next
Introduction to function type in TypeScript