RecapIn part 1 of this series we developed an API for searching and sorting HTML tables. We introduced some code reuse in part 2 but were dissatisfied with the boilerplate. Part 3 teased us with
keyof, a promising feature of the type system. In this final post we dig in and finally deliver the goods.
Mapped, Conditional Types
Mapped TypesTypeScript provides the ability to transform a type into another type using a mapping operation. Imagine we want to create a version of our
Persontype where all the fields are read-only: With that, you can tell the compiler to take an instance of the Person class And treat it as though it was written this way: Pretty cool trick if you decide to introduce immutability to an existing API, for example.
Conditional TypesConditions can be applied to types during mapping. Here we create a type that contains only the string fields on Person: That says
map k -> k if Person[k] is a string, otherwise map k -> never, which is a type that matches nothing. Effectively eliminating
'age'from the union. This is exactly what we need.
The Final Version
API ModificationsFirst we add some type aliases that are easier to digest than the raw definitions. And fix the hole in the TableSort API.
Application CodeThe compiler now prevents us from doing the wrong thing and code completion guides us to the right thing. Adding the
stringcolumns And the