patterntypescriptCritical
Declare and initialize a Dictionary in Typescript
Viewed 0 times
typescriptandinitializedeclaredictionary
Problem
Given the following code
Why isn't the initialization rejected? After all, the second object does not have the "lastName" property.
interface IPerson {
firstName: string;
lastName: string;
}
var persons: { [id: string]: IPerson; } = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};Why isn't the initialization rejected? After all, the second object does not have the "lastName" property.
Solution
Edit: This has since been fixed in the latest TS versions. Quoting @Simon_Weaver's comment on the OP's post:
Note: this has since been fixed (not sure which exact TS version). I
get these errors in VS, as you would expect:
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:
Note: this has since been fixed (not sure which exact TS version). I
get these errors in VS, as you would expect:
Index signatures are
incompatible. Type '{ firstName: string; }' is not assignable to type
'IPerson'. Property 'lastName' is missing in type '{ firstName:
string; }'.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 errorCode Snippets
var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an errorContext
Stack Overflow Q#15877362, score: 478
Revisions (0)
No revisions yet.