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 in TypeSript by Logan
• 1,580 points
43 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 by Nina
• 2,900 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 in TypeSript by Nina
• 2,900 points
16 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 in TypeSript by Nina
• 2,900 points
17 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 in TypeSript by Nina
• 2,900 points
28 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 in TypeSript by Nina
• 2,900 points
43 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 in TypeSript by Nina
• 2,900 points
7 views
+1 vote
4 answers

How to write nested dictionaries to a CSV file

Using DictWriter there is no need in ...READ MORE

answered Oct 18, 2018 in Python by Richard William
21,310 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 in TypeSript by Nina
• 2,900 points
33 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 in TypeSript by Nina
• 2,900 points
7 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP