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.

The scenario

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:

  • RGB
  • RGBA
  • HSL
  • HSLA
  • HEX
  • Length
  • Percentage
  • Decibel
  • Time
  • Transformation

For the sake of simplicity, our interface for these inline-style objects will only support one property; Thecolor property.

Image for post

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 stringor number values.

#javascript #polymorphism #typescript

Polymorphism in Typescript
3.15 GEEK