typeforce
Another biased type checking solution for Javascript.
Exception messages may change between patch versions, as often the patch will change some behaviour that was unexpected and naturally it results in a different error message.
Examples
var typeforce =var element = prop: 'foo'var elementNumber = prop: 2var array = element element elementNumber// supported primitives 'Array', 'Boolean', 'Buffer', 'Number', 'Object', 'String'// TypeError: Expected Number, got Array// array types// supports recursive type templating// maybe types// sum types// value types// custom types{if !typeforce return falseif valuelength !== 32 return falsereturn true}// => OK!// TypeError: Expected LongString, got String 'not long enough'
Protips:
// use precompiled primitives for high performance// or just precompile a templatevar type =foo: 'Number'bar: '?String'var fastType = typeforce// fastType => typeforce.object({// foo: typeforce.Number,// bar: typeforce.maybe(typeforce.String)// })// use strictness for recursive types to enforce whitelisting properties// OK!// TypeError: Unexpected property 'y' of type Number
Protips (extended types):
// OK!// TypeError: Expected property "0" of type Number, got String 'not a number'// OK!// OK!{thisx = 2}// OK!// Note, any Foo will do// OK!
Protips (no throw)
var typeforce =var value = 'foobar'if// didn't throw!console // never happenselseconsole// prints 'Oops, Expected Number, got String foobar'
Protips (async)
var typeforce = require('typeforce/async')
typeforce(typeforce.Number, value, function (err) {
if (err) return console.log(`Oops, ${typeforce.error.message}`)
console.log(`${value} is a number`) // never happens
})
WARNING: Be very wary of using the quacksLike
type, as it relies on the Foo.name
property.
If that property is mangled by a transpiler, such as uglifyjs
, you will have a bad time.