The page you requested is still being published. It should be available soon.


I'm on the verge of getting into TypeScript, but since all of my coding right now is solo, I don't think it's going to be as useful as if I were on a team. Nevertheless, I'm curious about how it might benefit me.

For whatever reason (maybe just that I'm a creature of habit, like everyone?), I don't like messing with new build processes, and am not yet sure how initializing TypeScript will work with my flow. So I figured I'd whip up a quick way to check types within functions in JS.

Odds are good I'm totally missing the main benefits of TypeScript. That's okay. This was fun, and quick, and I got to play with a few things (more es6 fun, some different loop approaches, etc.). Also, I should note that I got some insight on this from Todd Motto's helpful piece Understanding JavaScript types and reliable type checking.

`` const ensureType = (el, type) => { const elType = Object.prototype.toString.call(el).slice(8, -1); if (elType === type) { return true; } throw TypeError(Expected ${el} to be a ${type}, but it's a ${elType}.`); };

const ensureTypes = (elements) => { elements.forEach(([el, type]) => { ensureType(el, type); }); return true; }; ```

With this, you can check a single param with ensureType('avocado', 'String');, or you can check multiple params with ensureTypes([['bagel', 'String'], [6, 'Number']]);.

Simple example: function sum(a, b) { ensureTypes([[a, 'Number'], [b, 'Number']]); return a + b; } If you tried to evaluate sum(5, '5'), it'd throw an exception.

Not sure this will benefit anyone, but thought I'd share. Let me know if you end up using this for anything!