Optional typing in JavaScript without transpilers

Since I started to work with TypeScript I’m thinking “it’s really cool thing, but why should I waste so much time on writing and maintenance interfaces?”.

Well, this is a greatness and weakness of typed languages. In order to write robust applications you need to defined everything around.
And then… customer changes its requirements. GOTO step 1.
So using typed languages like TypeScript or Flow you have to keep in mind, that they enforce you:

  • Learn their own stuff
  • Define entities manually, before writing code

The second point I was thinking in terms of types in JavaScript were already existed data shape tools in JavaScript. It can be not so obvious, but when you deal with Swagger, Mongoose or React you already use some expressive tools to describe your data models.

So why not to reuse them and get all advantages of complex data types?

JavaScript is untyped and interpreted programming language, so the only solution to implement static types - is source code analysis tools. And one of the best of them is ESLint.

ESLint is mostly used for code styling, but it might seem at first sight only.

For example such rules as no-param-reassign, no-shadow or no-unresolved not allowed you to make mistakes writing code. Exactly the same is related to types: they enforce and restrict you to write code without errors.

TypeLint

All these thoughts have led me to writing a plugin for ESLint, which basically does types checking. In last several projects we actively use Swagger to describe APIs, which involves writing definitions on JSON Schema.

JSON Schema is a good and well documented standard and since 2 version it even supports inheritance. Every JS application manages JSON data and I actually wonder why JSON Schema is not still everywhere.

So what basically TypeLint does, it binds your already existing JSON schema models with special JSDoc notations and validate code that you write.

Configure your IDE according to using the plugin and voilà

In addition we can easily validate native types using existing JSDoc notation with curly braces.

Currently TypeLint supports only JSON Schema, but adapters for Mongoose and GraphQL schemas are in plans.

Check out the project and I hope it helps you to avoid a lot of bugs in future allowing to write code as fast as it needs your business requirements.