const trimIfExists = value => typeof value === 'string' ? value.trim() : value;
const str1 = new String('foo '); typeof str1; // 'object' trimIfExists(str1); // 'foo ' const str2 = new Object('foo '); typeof str2; // 'object' trimIfExists(str2); // 'foo '
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
Looking at the Lodash
method used above you can see there are a few cases it covers:
- Async Functions
Alternatives to manually checking types within your functions/methods: