How are collections typed in Typescript?
Primitives are fairly easy to type - we have seen this while discussing Typescript and its types.
|
|
We have seen examples of typed arrays in the same post, but how about all the other collections? How far down the typed rabbit hole are you willing to go?
Arrays
There are two useful notations - pick one, or both.
|
|
Tuples
Tuples, unlike arrays, have fixed number of elements. In Typescript, we just go about typing all of them.
|
|
Objects
Keys can have their own types in Typescript Objects.
|
|
You can use objects to instantiate the class..
|
|
Map
Just like Javascript, a map
is an object that stores a key-value pair.
|
|
The key and value can have any type - we just happen to use strings for both.
Set
A set
is an ordered list of values with no duplicates.
|
|
WeakMap and WeakSet
WeakMap
and WeakSet
behave like their strong counterparts, but with an object for key. They very much resemble what they can do in Javascript but with types.
Consider this example for WeakMap
..
|
|
.. and, for the WeakSet
.
|
|