30

Type Checking in JavaScript

 4 years ago
source link: https://medium.com/@tracker1/type-checking-in-javascript-6baa5ef55369
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

This is my response to a post on the topic . While it’s a nice post and accurate, I will say that I feel the approach and thinking is off. When using JS, you should stop thinking about Type validation, and start thinking of input validation.

aANv2yU.jpg!web

Photo by Irvan Smith on Unsplash

JS was first and foremost a way to validate input before sending it off to the server. Other bits came later. Truthy/Falsy detection should be the first thing you look at. The following values evaluate to false, everything else is true.

false  0  “” // empty string  undefined  null  NaN

If you look at the above, it starts to make sense. It’s a bit of a gotcha if you want to allow for an express 0.

(input || input === 0)

But for the most part, a simple if statement can handle the bulk of those verification cases. For an empty object.

(input && Object.keys(input).length)

For an array…

(Array.isArray(input) && input.length)

In the end, the approach can be really elegant and simple in practice. The problem is when you get tethered into treating JS like many other languages that behave differently.

If you’re really trying to match/verify a complex structure, that can get more cumbersome and you should probably look at one of the many schema validation libraries for JS. They’re sometimes called JSON Validators, but they are really Object Schema validation. For the most part, this type of validation is *really* only used on server implementations. Given how popular Node.js has become for server-side implementations, it is a valid concern, but there are many packages/solutions for this already.

So, to summarize, what is the key for Type verification in JavaScript? Stop trying to validate types and start validating input and/or schema structure.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK