Giter Site home page Giter Site logo

typeforce's Introduction

typeforce

Version

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

const typeforce = require('typeforce')

// supported primitives 'Array', 'Boolean', 'Buffer', 'Number', 'Object', 'String'
typeforce('Array', [])

typeforce('Number', [])
// TypeError: Expected Number, got Array

// array types
typeforce(['Object'], [{}])
typeforce(typeforce.arrayOf('Object'), [{}, {}, {}])

// enforces object properties 
typeforce({
  foo: 'Number'
}, {
  foo: 'bar'
})
// TypeError: Expected property "foo" of type Number, got String "bar"

// maybe types
typeforce('?Number', 2)
typeforce('?Number', null)
typeforce(typeforce.maybe(typeforce.Number), 2)
typeforce(typeforce.maybe(typeforce.Number), null)

// sum types
typeforce(typeforce.anyOf('String', 'Number'), 2)
typeforce(typeforce.allOf({ x: typeforce.Number }, { y: typeforce.Number }), {
  x: 1,
  y: 2
})

// value types
typeforce(typeforce.value(3.14), 3.14)

// custom types
function LongString (value, strict) {
  if (!typeforce.String(value)) return false
  if (value.length !== 32) return false
  return true
}

typeforce(LongString, '00000000000000000000000000000000')
// => OK!

typeforce(LongString, 'not long enough')
// TypeError: Expected LongString, got String 'not long enough'

Protips:

// use precompiled primitives for high performance
typeforce(typeforce.Array, array)

// or just precompile a template
const type = {
  foo: 'Number',
  bar: '?String'
}

const fastType = typeforce.compile(type)
// fastType => typeforce.object({
//   foo: typeforce.Number,
//   bar: typeforce.maybe(typeforce.String)
// })

// use strictness for recursive types to enforce whitelisting properties
typeforce({
  x: 'Number'
}, { x: 1 }, true)
// OK!

typeforce({
  x: 'Number'
}, { x: 1, y: 2 }, true)
// TypeError: Unexpected property 'y' of type Number

Protips (extended types):

typeforce(typeforce.tuple('String', 'Number'), ['foo', 1])
// OK!

typeforce(typeforce.tuple('Number', 'Number'), ['not a number', 1])
// TypeError: Expected property "0" of type Number, got String 'not a number'

typeforce(typeforce.map('Number'), {
  'anyKeyIsOK': 1
})
// OK!

typeforce(typeforce.map('Number', typeforce.HexN(8)), {
  'deadbeef': 1,
  'ffff0000': 2
})
// OK!

function Foo () {
  this.x = 2
}

typeforce(typeforce.quacksLike('Foo'), new Foo())
// OK!

// Note, any Foo will do
typeforce(typeforce.quacksLike('Foo'), new (function Foo() {}))
// OK!

Protips (no throw)

const typeforce = require('typeforce/nothrow')
const value = 'foobar'

if (typeforce(typeforce.Number, value)) {
  // didn't throw!
  console.log(`${value} is a number`) // never happens
} else {
  console.log(`Oops, ${typeforce.error.message}`)
  // prints 'Oops, Expected Number, got String foobar'
}

Protips (async)

const 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.

LICENSE MIT

typeforce's People

Contributors

dcousens avatar fanatid avatar mvayngrib avatar rubensayshi avatar sha49 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

typeforce's Issues

split on multiple files

It will easy for review if index.js will be divided on a few small files (native-types, other-types, one-of, may-be, etc).
@dcousens thoughts?

Optional error information

Type functions should probably just always return false rather than returning false or optionally returning an error object.
Maybe... I need to think further about this, but for now it has meant some back and forth like 9fa4135.

Avoid recursive throwing / return Error

Perhaps instead of true/false, instead return an Error object which can be thrown by the user.

Not sure if this can be done in a backwards compatible way, or if its worth it.

Ideally you'd still want to throw in the default case, but maybe a flag could manage that.
This would increase performance in the failing case dramatically.

typeforce 1.5.1 breaks bitcoinjs-lib 1.5.8

[email protected] has a dependency "typeforce": "^1.0.0"...

this means that it is forced to upgrade to typeforce 1.5.1... however, typeforce 1.5.1 doesn't seem to work in node 0.12.4

$ node node_modules/bitcoinjs-lib/node_modules/typeforce/lib/index.js 
/Users/williamcotton/Projects/fuckthis/node_modules/bitcoinjs-lib/node_modules/typeforce/lib/index.js:45
  Array(value) {
       ^
SyntaxError: Unexpected token (
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Is this valid JS? Under what version of node?

Please be careful with your semver releases!!!!!!!

Standard failing

@feross, not sure I understand, can you spot the problem?
Relevant code.

standard: Use Use JavaScript Standard Style (https://github.com/feross/standard)
/home/travis/build/dcousens/typeforce/src/index.js:121:22: Expected indentation of 6 characters but found 4.
/home/travis/build/dcousens/typeforce/src/index.js:127:20: Expected indentation of 6 characters but found 4.
/home/travis/build/dcousens/typeforce/src/index.js:133:20: Expected indentation of 6 characters but found 4.

See https://travis-ci.org/dcousens/typeforce/jobs/74659788

isFiniteNumber?

I think it will be helpful (and don't require many efforts).

Allow for direct Function type passing over 'just' strings

This resolves issues with the name resolution being different to what a user expects.

foobar.js

module.exports = function Pears() {}

script.js

var typeforce = require('typeforce')
var Foobar = require('./foobar')

var f = new Foobar()
// ...

typeforce('Foobar', f) // throws, Pears !== Foobar

Change quacksLike to check expected properties, not name

@weilu you mentioned this in 3c8499b, however to enforce this we would need to pass in the type value as it stands and then build an actual type structure from that object.

Aka

var x = { a: 1 }
var y = { b: 1 }

var tx = typeforce.quacksLike(x)
// returns equivalent of { a: "Number" }

typeforce(typeforce.quacksLike(x), y)
// TypeError: Expected property "a" of type Number, got undefined

Thoughts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.