Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript: How to ensure that a parameter has a specific interface?
    text
    copied!<p>Edit: I found this interesting library which looks like it can do exactly what I was describing at the bottom: <a href="https://github.com/philbooth/check-types.js" rel="nofollow">https://github.com/philbooth/check-types.js</a></p> <p>Looks like you can do it by calling check.quacksLike.</p> <hr> <p>I'm fairly new to using javascript and I'm loving the amount of power it offers, but sometimes it is too flexible for my sanity to handle. I would like an easy way to enforce that some argument honors a specific interface.</p> <p>Here's a simple example method that highlights my problem:</p> <pre><code>var execute = function(args) { executor.execute(args); } </code></pre> <p>Let's say that the executor expects <code>args</code> to have a property called <code>cmd</code>. If it is not defined, an error might be caught at another level when the program tries to reference <code>cmd</code> but it is <code>undefined</code>. Such an error would be more annoying to debug than explicitly enforcing <code>cmd</code>'s existence in this method. The executor might even expect that <code>args</code> has a function called <code>getExecutionContext()</code> which gets passed around a bit. I could imagine much more complex scenarios where debugging would quickly become a nightmare of tracing through function calls to see where an argument was first passed in.</p> <p>Neither do I want to do something on the lines of:</p> <pre><code>var execute = function(args) { if(args.cmd === undefined || args.getExecutionContext === undefined || typeof args.getExecutionContext !== 'function') throw new Error("args not setup correctly"); executor.execute(args); } </code></pre> <p>This would entail a significant amount of maintenance for every function that has arguments, especially for complex arguments. I would much rather be able to specify an interface and somehow enforce a contract that tells javascript that I expect input matching this interface.</p> <p>Maybe something like:</p> <pre><code>var baseCommand = { cmd: '', getExecutionContext: function(){} }; var execute = function(args) { enforce(args, baseCommand); //throws an error if args does not honor //baseCommand's properties executor.execute(args); } </code></pre> <p>I could then reuse these interfaces amongst my different functions and define objects that extend them to be passed into my functions without worrying about misspelling property names or passing in the wrong argument. Any ideas on how to implement this, or where I could utilize an existing implementation?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload