Categories
TypeScript Answers

How to declare and initialize a dictionary in TypeScript?

Spread the love

Sometimes, we want to declare and initialize a dictionary in TypeScript.

In this article, we’ll look at how to declare and initialize a dictionary in TypeScript.

How to declare and initialize a dictionary in TypeScript?

To declare and initialize a dictionary in TypeScript, we can create a dynamic object type.

For instance, we write

const persons: { [id: string]: IPerson } = {};
persons["p1"] = { firstName: "jane", lastName: "smith" };

to set the persons variable to type { [id: string]: IPerson }.

[id: string] is the data type for the object keys and IPerson is the data type for the values.

Then we write

persons["p1"] = { firstName: "jane", lastName: "smith" };

to add entries into persons where { firstName: "jane", lastName: "smith" } follows the structure of IPerson.

Conclusion

To declare and initialize a dictionary in TypeScript, we can create a dynamic object type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *