TypeScript Code Smell Any instead of a type parameter
Posted on April 2, 2025 by Michael Keane GallowayI was recently forking a TypeScript library at work. We had an existing library that does a lot of what we want that we want to refactor to use a new backend, but we want to leave the current implementation alone. I won’t completely unpack this, but we decided to create a fork and refactor.
While I was setting up the new repository, I noticed that the library that I
was grabbing had about 20 linting errors. All of these errors were related to
the use of any
. I also noticed that they were mostly used instead of having a
generic type parameter.
For example, if there was an array concatenation function in the library it would have been written with the following signature:
function concat(a : any[], b : any[]) : any[]
This would take two arrays of any
type and return an array of any
type.
Generally any
should be avoided. It makes it harder for the transpiler to
reason about your code and prevents checks for certain kinds of bugs. With that
in mind, it was pretty straightforward to change these kinds of signatures to
use a generic type parameter:
function concat<T>(a : T[], b : T[]) : T[]
Now the type system can reason more about what this function is and how it interacts with the type system.
I went about fixing all of the linting errors. Merged my new baseline code to start development. I then spent a little bit of my time during stand up to announce the code smell that I found and how address it. After that I thought it might be a good idea to reach out to the original developer who is currently on another team.
I brought up a sample from the code base and how I modified it to fix the linting error. His response was something along the lines of “oh I hadn’t considered that!” We discussed this a little bit more on how to leverage this knowledge to help his new team.
The results of this episode is that our code was slightly improved, but more importantly our developers gained some knowledge that should make them more effective.