Resolved: How to write a function which takes a dynamic key and an item and pushes it to object[key]?

In this post, we will see how to resolve How to write a function which takes a dynamic key and an item and pushes it to object[key]?

Question:

I have several objects and types:
I want to define a function that takes two arguments:
  • dynamic key (“cars” or “books”), and
  • an item (which will respectively be of ICar or IBook)

and pushes item to stuff[key].
Also when calling the function I want it to infer the type of an item based on the key and autosuggest keys.
What I’ve tried is this:
here is the link of the ts playground

Best Answer:

In order to make it work, you need to create higher order function which is context agnostic. Consider this example:
As you might have noticed, I have added a higher order function to addToStuff. Now it is withStuff which returns addToStuff. You can also use any other data structure where each value is an array, not only Stuff data shape.
Playground
You can find more examples with currying in my article.

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com