DEV Community

Discussion on: TypeScript vs JavaScript🤔

 
joelbonetr profile image
JoelBonetR 🥇

Hi Nathan, I agree mostly with this, types are extra safety you add into the code at a cost of some burden in maintenance.

The issue comes with code like that

  function add(a:number,b:number):number {
     return a + b 
 }
Enter fullscreen mode Exit fullscreen mode

You've a sense of calm and safety because you added :number but we all know that contextual information about types is removed during compilation because we compile to pure JavaScript, which doesn’t know the types at runtime.
This behavior does not provide any kind of safety mechanism against incorrect or invalid inputs, such as inputs from unhandled API endpoints, libs, form inputs...
TypeScript is not designed to provide input constraints that are at an advanced level of type safety.

You can add type guards, validation libraries or manual checks in critical paths, of course (so you can in JS, see (prop-types)[npmjs.com/package/prop-types] or (Joi)[npmjs.com/package/joi] as examples).

Another way to workaround that is simply to (avoid runtime errors)[softwareengineering.stackexchange....].

const add = (...args) => args.reduce((p, c) => (Number.parseFloat(p) || 0) + (Number.parseFloat(c) || 0));

add(true, 3) // 3
add(false, 3) // 3
add('hey', 3) // 3
add('hey', true) // 0
Enter fullscreen mode Exit fullscreen mode

You can do the same with TS as well of course.
While 0 may represent a wrong result in this case

add(1, -1) // 0
add('hey', true) // 0
Enter fullscreen mode Exit fullscreen mode

You may either design it on a way it's not important or return an arbitrary value that you can check in the caller or keep bubbling the "wrong value" if the path is not critical (i.e. does not alter business logic, doesn't have side-effects and so on).

On the tests thingy... While type check tests are considered trivial for static typed languages in some codebases, my experience (and probably yours as well) says that runtime errors/exceptions due to wrong types happen either be JS, TS, Java... so maybe they are not so trivial at the end.

Both things together (static type checks and unit tests) are a win-win in code confidence terms. If you're not ensuring types in tests (overall) maybe consider adding them through paths that are dependant on third parties or other repos just in case.