📦 Building polymorphic components in TypeScript (#43)
August 10, 2021
Yesterday, I wrote to you about building polymorphic components. For those of you who missed it, the term “polymorphic” describes a single component that can render 2 or more HTML elements under the hood.
Building components in TypeScript provides significant value: having a type-safe component API can improve the developer ergonomics of your component library because it prevents your users from passing incorrect data by warning them at compile-time.
It does add an additional layer of challenge to building polymorphic components, because it’s not sufficient to only define the properties available on a single element (like a <button />). Instead, you must define the properties available on any element the component can render under the hood.
In other words, a polymorphic Button component must allow an href prop when the as=“a”, but it can’t allow that same prop when as=“button”.
In this first example, there should be no TypeScript warning:
<Buttonas="a"href="www.google.com"/>// no TypeScript warning
In this second example, there should be a TypeScript warning: