paldepind / union-type

A small JavaScript library for defining and using union types.
MIT License
477 stars 28 forks source link

More informative error messages #46

Open wishfoundry opened 8 years ago

wishfoundry commented 8 years ago

currently union-type emits an error when given the wrong input type:

"wrong value #{ value } passed to location #{ numToStr[i] } in ${ name }"

it would be nice if the gave the expected type and well as the given type

paldepind commented 8 years ago

I agree. That would be a very nice addition.

JAForbes commented 8 years ago

And if the type was created with keys, it'd be great to see the key of the property that was invalid instead of the location.

e.g.

TypeError: property x should be a Number but instead was a String

I guess that is hard with predicate types, because they do not have names. But we could get a lot of value still from built in types and UnionType types.

Maybe for predicate types we could have a special type error.

TypeError property y should satisfy: typeof value == "number"

Where we grab the predicate from the function body?

Might be good too to detect UnionType curried functions specifically and offer a hint when another type receives a partially applied type as input.

TypeError: You are passing curried type ${typename} as input to another type: ${typename2}.  

${typename} is missing arguments: ${remainingArgs}, you need to populate them before passing them
to ${typename2}

Or something to that affect.

On that note, it'd be great to get type checking as the function receives applications instead of waiting for every argument. It'd require a custom curry in order to hook into receiving values, but it would be worth it.

E.g.

var Point = Type({
  Point: { x: Number, y: Number }
})

// invalid type, but we don't hear about it until later
var p = Point.Point('1') 

// Now we receive the type error for the 1st arg
// But we could have told the user earlier.
p(2)

I'd be happy to help out implementing any of these ideas if they sound like a good fit?