It’s not uncommon for people to think of Object-Oriented Programmingand Functional Programmingas mutually exclusive, and understandably so; any discussion involving the two turns quite often into a debate where rivalry is the central theme. But as it turns out, in some contexts, we can benefit from employing disciplines from both paradigms to get the best of two worlds. **Ad-hoc Polymorphism **in Typescriptis one such context.
Consider the case where we’re developing an inline-styling library. The library has different types that correspond to different CSS data types, such as:
For the sake of simplicity, our interface for these inline-style objects will only support one property; Thecolor
property.
As demonstrated in the photo above, the value of the color property in our interface has a tagged-union type, which consists of a stringLiteral
type and five other custom types represented as Javascript objects and modeled after the nominal-typing model described in my previous article.
Now, within the boundaries of the library’s code, these types are well understood, and their values can be manipulated accordingly, but outside these boundaries — say in React, for example — they bare no meaning. For React to utilize these values for styling, we need to serialize them into either string
or number
values.
#javascript #polymorphism #typescript