Given the following code
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.
A collection of key and value pairs is called a dictionary in TypeScript. The dictionary is also referred as a map or a hash. A map can be created by using the type Map and the keyword new. We can store the collection of key value pairs inside a map by creating a map.
A dictionary is a data type that maps from keys to values, and allows you to get the value for a given key in O(1) time. In Typescript or Javascript, you can use an Object as a dictionary: const dictionary = { 'key1': 'value1', 'key2': 'value2' }; console.
To declare a function with an object return type, set the return type of the function to an object right after the function's parameter list, e.g. function getObj(): {name: string;} {} . If the return type of the function is not set, TypeScript will infer it.
In this Blog Post, Learn the dictionary in typescript with examples. Dictionary is a type of data structure with unordered list data, that contains key and value values. It is the same as map type in typescript.
I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking.
The first initialization uses the Add method with two arguments. The compiler generates a call to Add for each of the pairs of int keys and StudentName values. The second uses a public read / write indexer method of the Dictionary class: Note the two pairs of braces in each element of the collection in the first declaration.
We can use any in a type annotation, but then no type checking will occur on the dictionary: We want some type checking to happen but have the flexibility to add keys into the dictionary at runtime. Here we specify that the dictionary keys are strings and the values are numeric. The “name” label can be anything we like. Often “key” is used:
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:
Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With