DEV Community

Tane Piper
Tane Piper

Posted on

Typescript tip: Don't use "naked any", create an "any interface" instead.

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

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.

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.

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:

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:

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!

Top comments (1)

Collapse
 
michaeljota profile image
Michael De Abreu • Edited

This is actually quite helpful, and in deed there are only a few moments in development that you honestly don't know what is the shape of the object you are going to use. Still, a named object is better than anything.

Update: unknown type is landing in TS 3. So, we shouldn't need awkward anymore