← til

Enforcing strong parameters

December 19, 2018
javascript

In order to enforce strong parameters in JavaScript, à la Ruby, you can provide a function that checks the existence of the paramater as a default parameter.

const required = p => { throw new Error(`Missing parameter: ${p}`) }

class FancyStruct {
  constructor({ type = required("type"), value = required("value")} = {}) {
    this.type = type
    this.value = value
  }
}

new FancyStruct() // Uncaught Error: Missing parameter: type
new FancyStruct({ type: "foo" }) // Uncaught Error: Missing parameter: value

const struct = new FancyStruct({ type: "foo", value: "bar" }) 
struct.type  // "foo"
struct.value // "bar"

Even better, you can use tagged templates to shorten the invocation of the helper function.

const req = p => { throw new Error(`Missing parameter: ${p}`) }

class FancyStruct {
  constructor({ type = req`type`, value = req`value` } = {}) {
    this.type = type
    this.value = value
  }
}

const struct = new FancyStruct({ type: "foo", value: "bar" }) 
struct.type  // "foo"
struct.value // "bar"

Credits

Mark Tiedemann's Gist