Weekly Webtips
Published in

Weekly Webtips

How To Camelize Object Typing in TypeScript Without Any Library

Photo by Blake Connally on Unsplash

🕵️ Time To Probe

  • CamelizeString is a custom type that “accepts” a string. That’s how we can read the <ObjectProperty extends string> part. If the passed generic type isn’t a string, then it will throw an error.
  • Once we are able to pass a type string, it then checks if the string is in snake_case and returns as is if not in snake_case.
  • Using Template Literal String Types we were able to conditionally check if the passed type is on snake_case and convert it otherwise, return as is.
  • Camelize is a custom type that “accepts” a generic type object. Unlike CamelizeString, this custom type accepts any object.
  • On line 2, what we are doing is “loop” into the passed generic type object, grab each property and assign it to “ObjectProperty”. And then lastly, convert or force cast “ObjectProperty” to a CamelizeString. This would essentially convert the object key from snake_case to camelCase.
  • As we are looping on each property with the passed generic type object, we then check if the generic type object property value is an array or an object.
  • It is basically doing something if obj[prop] is an Array, check if the item in the Array is an object. If it is an object, iterate and camelize each property, otherwise, return it as is. You can think of it as a nested transformation. The nested ternary isn’t beautiful and hard to understand but hopefully the tabbing allows you to see the respective flow.

🚀 Bringing It All Together

TypeScript playground

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store