←back to thread

Parse, Don't Validate (2019)

(lexi-lambda.github.io)
389 points melse | 2 comments | | HN request time: 0.421s | source
Show context
mirekrusin ◴[] No.27640199[source]
In typescript parsing/asserting types with combinators works very well merging runtime with static type system [0], it has to be used at i/o boundary, then it enters static type system guarantee and no assertions are necessary, makes very nice codebase.

[0] https://github.com/appliedblockchain/assert-combinators

replies(1): >>27640428 #
lloydatkinson ◴[] No.27640428[source]
I wish it had actual proper examples. I've no idea how to use that.
replies(3): >>27640723 #>>27642258 #>>27642707 #
1. uryga ◴[] No.27640723[source]
from a look at the readme, you combine those `$.TYPE` things to build a validation function that checks if its argument matches some pattern (and throws an exception if it doesn't).

  import * as $ from '@appliedblockchain/assert-combinators'

  const validateFooBar = (
    $.object({
      foo: $.string,
      bar: $.boolean
    })
  )
  // probably roughly equivalent to
  /*
  const validateFooBar = (x) => {
    console.assert(
      typeof x === 'object' &&
      typeof x.foo === 'string' &&
      typeof x.bar === 'boolean'
    )
    return x
  }
  */


  const test1 = { foo: "abc", bar: false }
  const test2 = { foo: 0, quux: true } 
  const { foo, bar } = validateFooBar(test1) // ok
  const oops = validateFooBar(test2) // throws error
the source is pretty readable too if you want to get an idea how it works.

https://github.com/appliedblockchain/assert-combinators/blob...

https://github.com/appliedblockchain/assert-combinators/blob...

replies(1): >>27661606 #
2. mirekrusin ◴[] No.27661606[source]
Yes, the difference between console.assert and assert-combinators is that assert combinators return well typed ts result (and are more terse/minimal).