A few days ago I had a problem in TypeScript where I should have used generic types, but I did not have enough experience with TypeScript. So, as any developer would have done, I searched the web for information about the issue and how I could solve it.
The problem is this: I have an interface with several properties. One of them should be of one type sometimes and of another type other times.
My first approach to solve my issue was this:
Clearly, this was not the best solution, since when trying to implement this interface the type for data was not correct at the assigning moment. I got the following error: MyDataInterface is not assignable to MyDataInterface | MySecondDataInterface. Definitely a rookie mistake.
The correct solution should be to use a generic type like this:
This way, data could be any type. The implementation could be done creating a type like this:
Now let’s talk about the subject of the article. Remember, I am a rookie in terms of TypeScript. So when I searched Google for the solution for my initial problem, the term I used was “TypeScript placeholder.” Google was smart enough to return some results that I could use, or at least could be a starting point.
The first result was a GitHub discussion about a new proposal for TypeScript called exactly the same thing: “TypeScript placeholder declaration”. Let’s be clear about something first: the Placeholder Declaration has nothing to do with my initial problem. Generic Types solved my issue.
The Placeholder Declaration proposal covers the occasions when a user needs to express that a type could exist depending on the environment (web or node) in which the code will run. A common example is this:
Someone that uses a library with this feature would need to say not only that the type Buffer exists but supports some operations. To do so, they could add those operations properly:
What I personally got from reading this whole thread of responses to the proposal was great. It helped me understand many other TypeScript concepts that I did not know until now, and helped me to fall in love a little more with TypeScript. Such a simple problem (as I see it now), such as generic types, led me to this discussion that helped me to understand a lot of things, as well as to follow these people who have a lot to contribute.
The discussion lasted a full year until June 17, 2020, and remains open to this day almost two years later. Unfortunately, it has not concluded and this new functionality has not been added to TypeScript, but it could be added in the future. For more information go to this link.
We’d love to learn more about your project.
Engagements start at $75,000.