Type Checking In JavaScript Is Tricky

Type checking is tricky in JavaScript. Here is a recent example I encountered:

const trimIfExists = value => typeof value === 'string'
  ? value.trim()
  : value;

There is a subtle bug in the above code and something to think about when performing type checking in JavaScript. For example the following will not be trimmed by using the above function:

const str1 = new String('foo ');
typeof str1; // 'object'
trimIfExists(str1); // 'foo '

const str2 = new Object('foo ');
typeof str2; // 'object'
trimIfExists(str2); // 'foo '

I think you should generally avoid type checking. JavaScript is a dynamically typed language. If you want to call a method on a value then you should just check if it has that method and if it is callable. This is duck typing.

Performing duck typing rather than type checking allows more flexibly. This allows you to do polymorphism in places where you need it. For example, if you want to call trim we should look to see if the value has a trim method/callable property. Use the ‘in’ built-in because it is the only method that will find it anywhere in the inherence chain.

const _ = require('lodash');

const isPropertyCallable = (val, property) => property in val && _.isFunction(val[property])

const trim = (val = '') => isPropertyCallable(val, 'trim')
  ? value.trim()
  : val

If you really do need to perform type checking in JavaScript (and I think you may be able to do less of it than you think) then use a proven, hardened library like Lodash to check the type.

Looking at the Lodash isFunction method used above you can see there are a few cases it covers:

  • Functions
  • Async Functions
  • Generators


Alternatives to manually checking types within your functions/methods: