Why are Dictionary<k,v>
's on interfaces a bad idea?
Thanks
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.
An immutable object is defined as an object that cannot be changed after it has been created.
Use an index signature to define a key-value pair in TypeScript, e.g. const employee: { [key: string]: string | number } = {} . An index signature is used when we don't know all the names of a type's keys ahead of time, but we know the shape of their values. Copied!
Use the set() method to add a key/value pair to a Map , e.g. map. set('myKey', 'myValue') . The set() method adds or updates the element with the provided key and value and returns the Map object.
Because even if you make them readonly
or const
, that doesn't stop clients from modifying the contents of the dictionary (without your provision). The same applies to arrays and lists on public interfaces.
To address this problem, you can either give a copy of the container to the client (as jk mentioned in his/her comment), or (would it be too expensive to copy the whole container) provide accessor methods to it like getItem
and setItem
. This way you keep control of the contents of the container.
If you need trigger actions when the dictionary is modified or restrain the access to it (forbid removal as an example) you have to provide in your interface methods that wrap the dictionary. Moreover, you'll gain flexibility if you want to replace the underlying container, in that case the dictionary.
The List<>
has a nice feature : the AsReadOnly()
method that returns a IList<>
implementation that is read only.
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