How to initialize an object in TypeScript?

Sometimes, we want to initialize an object in TypeScript.

In this article, we’ll look at how to initialize an object in TypeScript.

How to initialize an object in TypeScript?

To initialize an object in TypeScript, we can create an object that matches the properties and types specified in the interface.

For instance, we write

export interface Category {
  name: string;
  description: string;
}

const category: Category = {
  name: "My Category",
  description: "My Description",
};

to create the Category interface with the name and description string properties.

Then we create the category Category variable which has the same properties set to strings so that the properties and types matches the interface exactly.

We can also make the properties optional by putting ? after the property name, so we write

export interface Category {
  name?: string;
  description?: string;
}

to make name and description optional.

Conclusion

To initialize an object in TypeScript, we can create an object that matches the properties and types specified in the interface.