Typescript tip: Don’t use “naked any”, create an “any interface” instead.

Tane Piper
May 7, 2018 · 3 min read

One of the get out clauses that Typescript provides is the use of the any type in your code base. At the time of creating our first implementation we might not know the complete shape of our object and we might be tempted to overload our functions with lots of logic

Image for post
Image for post

The code isn’t very descriptive in some ways, at least where Typescript is concerned. Instead of using this any, we can create an interface that allows the code to be more descriptive while still giving flexibility during development.

Image for post
Image for post

Already this is much better! We know we are getting an OldModeland we are going to get a newModel so later in our code we’ll be able to call up methods and properties we might attach to it. The compiler won’t complain either and give you the ability to focus on enhancing your type.

Another added benefit is in Code you can Alt or Ctrl + Click on the interface from anywhere to see it’s shape, and see if you are missing properties.

But as our model begins to be used, we begin to see the types we want to create.

Image for post
Image for post

We haven’t finished extracting all the features of the OldModel just yet so we leave in the [key:string]: any on the main object. The properties also receives this because we want to retain that flexibility. If you need to you could be more strict actually set the values as a list of specific types like:

Image for post
Image for post

This would at least ensure your property was reasonably strictly enforced to one of these types.

You could even go further and create a class for your type:

Image for post
Image for post

Our NewModel we want to lock down so we remove this from it. From here you can make your code more readable, testable and can refactor out complex logic down to type comparison and object creation.

Hopefully using this technique will help your codebase too!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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