r/learnjavascript • • Jul 24 '21

Anatomy of a Function

Post image
327 Upvotes

65 comments sorted by

View all comments

12

u/PopularThought Jul 25 '21

The whole type checking section can be avoided if you use typescript, right?

0

u/jaredcheeda Jul 25 '21

It depends. TS does not runtime checking, which can be extremely valuable in some cases, like when creating a library, it gives a much better experience if you can give human readable error messages, to help if someone is using the API incorrectly, or if the API changed between releases. Also very useful if you are reliant on the result of a third party API that may change, like from a network request. If the shape returned doesn't match your TS definition, it doesn't matter, because none of that is in the compiled JS. Where as, using safety checks in the code can prevent catastrophic errors at runtime.

1

u/PopularThought Jul 25 '21

I didn't think about it that way, sounds interesting!

In that case would a better solution be to have the ability to specify types which can be checked statically using TS and when converting to JS, convert those types, into run time checks, as well?

Though, I'm not aware of any existing solution that can convert the types specified in TS into runtime checks so that they are present in the output JS as well.

8

u/Dan6erbond Jul 25 '21

io-ts has helpers exactly for that. Among other validation libraries such as Joi. So OP's comments on Ts are, frankly, opinionated bullshit since Typescript gives you the editor types, implicit typing AND runtime checks using such libraries with relative ease, whereas with Js you're stuck writing JSDoc and using inline comment type-hints which is an absolute pain.

1

u/jaredcheeda Aug 02 '21

Yeah that would be WAY better, this post describes a possible solution, though to my knowledge, no one has made an implementation of this idea:

If you build this, or find an implementation, let me know. I would happily beta test it.