To find the intersection of two maps in TypeScript we need to iterate over one of the maps and check if the key exists in the other map.
Here's an example function that takes two maps and returns their intersection as a new map:
index.ts384 chars15 lines
Here we've defined a generic function that takes two maps of any key and value types. We create a new map that will hold the intersection, which we'll return at the end. We then iterate over the keys in the first map, and check if each key exists in the second map. If it does, we add the key-value pair to the result map.
Note that we're using the non-null assertion operator !
when getting the value from map1
. This is safe since we know that map1
has the key since we're iterating over its keys.
We can then call this function with two maps of our choice to find their intersection:
index.ts240 chars14 lines
Here we're creating two maps containing some key-value pairs. We then call our intersection
function passing both maps as arguments. The resulting map contains only the key-value pairs that are present in both maps, which is b: 2
and c: 3
.
gistlibby LogSnag