josdejong / typed-function

Runtime type-checking for JavaScript functions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot merge typed functions with simple type system

gwhitney opened this issue · comments

Consider

typed.types = [
  { name: 'number',    test: x => typeof x === 'number' },
  { name: 'string',    test: x => typeof x === 'string' }
]

const vanilla = typed({number: n => n+2})
console.log('Vanilla', vanilla(2))

const sprinkles = typed(vanilla, {string: s => s + ' two'})
console.log('With sprinkles', sprinkles('cookie'), sprinkles(3))

Looks perfectly innocuous, yet it fails with TypeError: Unknown type "Object".
Somehow, the infrastructure should not crumble because the the client just wants a few types...

I think you want to merge two typed functions, however, in following line:

const sprinkles = typed(vanilla, {string: s => s + ' two'})

the second argument is no typed-function but a plain Object. I guess it will work if you do

const sprinkles = typed(vanilla, typed({string: s => s + ' two'}))

If that works please let me know, I would like a cookie with sprinkles too 😋 .

It would be nice though if we could make the error message more informative at least, or extend the API to support this too.

Ah, right. Taking Object out of the type system simply makes it so that typed-function can't generate the proper error message (I didn't realize my syntax never worked so far, although I don't see any reason why it shouldn't). So this isn't as big a problem, but it is still a problem. I will file a PR so that typed-function doesn't depend on the type system to generate this error message.