January 12, 2021
Often I need to find what is the type of given variable so I could
decide how to handle it or what methods I may expect. At the same time using
typeof
is not always the solution we need. For example typeof []
will return
object
that is because arrays are extended objects but it’s not what we want to get.
There is Array.isArray([])
that will return boolean but again we need to check for
multiple types.
Function below gonna returning string value of the passed variable:
1function type(value) {2 return Object.prototype.toString3 .call(value)4 .replace(/\[object |\]/gi,'')5 .toLowerCase();6}
I’m going with .toLowerCase()
just to not relay on capital latters when comparing types.
After all we are working with exact string matching later on.
Let’s write a test about it to be sure that everything is as expected:
1describe('type', () => {2 it('should return the correct type', () => {3 [4 ['map', new Map()],5 ['set', new Set()],6 ['weakmap', new WeakMap()],7 ['object', {}],8 ['string', 'Hello'],9 ['array', []],10 ['boolean', true],11 ['number', 5],12 ['function', () => {}],13 ['date', new Date()],14 ['generatorfunction', function* generator() {}],15 ].forEach(([expectedType, value]) => {16 expect(type(value)).toBe(expectedType)17 })18 })19})
The test is not very extensiv or cover all posible cases but still - show that in most common cases it’s working.
In the cases where we need to accept for example two or more types, now there is a simple way of checking them
without writing multiple if
:
1function oneOfType(value, types) {2 return (types || []).includes(type(value))3}45const foo = 'must-be-string'67if (oneOfType(foo, ['string', 'array'])) {8 console.log(foo.length)9}
My name is Bozhidar Dryanovski and I'm a Software Engineer at Clarity
You should follow me on Twitter or Check my work at Github