DEV Community

Cover image for Do you use Static Typing in JavaScript?
Nick Taylor
Nick Taylor

Posted on • Updated on • Originally published at iamdeveloper.com

Do you use Static Typing in JavaScript?

I wrote an article last year, Consider Using TypeScript, to explain some of the benefits of using TypeScript and I'm just curious for those in the JS ecosystem if you use a language like TypeScript, Reason ML, or Facebook's Flow type checker.

This short post on the 2ality blog is relevant and a good read as well.

If you currently don't use one of the above, are you considering trying one of them? If you did try or use one of them, what kinds of issues, if any did you have? Difficult to setup? Learning curve etc.

Top comments (4)

Collapse
 
nektro profile image
Meghan (she/her) • Edited

This is why I don't use Flow. The function should take precedence.

// @flow
function square(n) {
  return n * n; // Error!
}

square("2");

Reason got rid of constand template strings, requires | to define and array, can't use function to define a function, replaced throw new Error with raise(Error(, and made blocks act like functions.

TypeScript is actually pretty nice but I try to stay away from having a build process if I can and Vanilla JS usually does me just fine and I like having full control over my code so I don't bother.

All in all, I'd love if JavaScript had static typing but for right now I don't use compilers for it.

Collapse
 
nickytonline profile image
Nick Taylor

I haven't used Flow, but I'm not following your comment. Do you mean that the coerced value 2 from "2" should pass here?

Collapse
 
nektro profile image
Meghan (she/her)

The way that I interpreted this example from their homepage is that the type checker is assuming that n should be a Number since the function uses n * n which is fair, but then the function is called with the String and it says the error is in the function and I believe that the function definition should take precedence on which type is "right".

Thread Thread
 
nickytonline profile image
Nick Taylor

Maybe it's not clear on their site., The function definition takes precedence like you thought it should.

Here's the example on their site:

// @flow
function square(n: number): number {
  return n * n;
}

square("2"); // Error!

What they're showing here is that the type checker won't allow you to call the function with a string.