How to declare and initialize a Dictionary in Typescript

0 votes

Why is this code not working as intended?

interface IPerson {
   firstName: string;
   lastName: string;
}

var persons: { [id: string]: IPerson; } = {
   "p1": { firstName: "F1", lastName: "L1" },
   "p2": { firstName: "F2" }
};
May 31, 2022 in TypeSript by Logan
• 2,140 points
2,220 views

1 answer to this question.

0 votes

Apparently this doesn't work when passing the initial data at declaration. I guess this is a bug in TypeScript, so you should raise one at the project site.

You can make use of the typed dictionary by splitting your example up in declaration and initialization, like:

var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error
answered May 31, 2022 by Nina
• 3,020 points

Related Questions In TypeSript

0 votes
1 answer

How to define props in TypeScript where a parent component injects props in its children?

Typescript doesn't remove this special rule "!text" ...READ MORE

answered Jun 16, 2022 in TypeSript by Nina
• 3,020 points
634 views
0 votes
1 answer

How to create ES6 Map in Typescript

Refer this as an example this.configs = new ...READ MORE

answered May 31, 2022 in TypeSript by Nina
• 3,020 points
92 views
0 votes
1 answer

TypeScript: How do you loop through a dictionary?

To loop over the key/values, use a for ...READ MORE

answered May 31, 2022 in TypeSript by Nina
• 3,020 points
279 views
0 votes
1 answer
0 votes
1 answer

Interface type check with Typescript

You can achieve what you want without ...READ MORE

answered May 31, 2022 in TypeSript by Nina
• 3,020 points
2,375 views
0 votes
1 answer

Difference between interfaces and classes in Typescript

Interfaces Describe how an object should look Exists compile ...READ MORE

answered Jun 15, 2022 in TypeSript by Nina
• 3,020 points
71 views
0 votes
1 answer

How to install and run Typescript locally in npm?

It took me a while to figure ...READ MORE

answered Jun 8, 2022 in TypeSript by Nina
• 3,020 points
1,391 views
0 votes
1 answer

How to typecast a string to number in TypeScript?

You can use the parseInt or parseFloat functions, or simply use ...READ MORE

answered Jun 9, 2022 in TypeSript by Nina
• 3,020 points
68 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP