DEV Community

Dominic Myers
Dominic Myers

Posted on • Originally published at drmsite.blogspot.com on

Type checking JavaScript


By Adam Drobiec

I read an article yesterday by Gil Tayar, which was fascinating. In it, he talked about his journey from strongly typed languages to untyped languages and back again. I'd recommend reading the article; it's well written and very informative.

His main gist seemed to be that TypeScript wasn't all that bad. I agree, and I've used it on and off for ages, I think I even have a certificate for a course somewhere, but I'm all for the flexibility of JavaScript.

Anyway, after reading it, I thought I'd give it a go, mostly as I wrote something a little while back which already implemented JSDocs. The process wasn't all that hard but was a bit of a faff. The odd wobble came from destructuring arguments in one of the constructors of one of the toy car child classes, and I was blown if I could understand the differences between String and string types until I read up some more. There were a few such quibbles, and TypeScript had issues with a few of my more relaxed approaches to JavaScript - such as explicitly checking for the existence of variables using !!. You can check out some of the other changes on a branch on GitHub.

I'm not sure I'll do it again, but it was worth spending a little while playing with it last night. It certainly would help in terms of distributing code to other developers, especially in terms of the automatic type checking offered by many IDEs and editors. I'm not overly sure of the strict setting - I like the whole fast and loose aspects of JavaScript quite a lot but, indeed, if I were to upload an NPM package I'd be inclined to be a little more rigorous.

Top comments (1)

Collapse
 
curtisfenner profile image
Curtis Fenner

What did you mean by TypeScript not being happy with checking for the existence of variables with !!? TypeScript is perfectly happy to do that:

const a: number | null = myFunction();
if (!!a) {
    const b: number = a; // typechecks
}
Enter fullscreen mode Exit fullscreen mode

I find myself far more productive in TypeScript because it lets me plan more (by writing types before the implementation, which often exposes silly things that I can fix before writing a lot of code) and generally be more hasty while still having confidence that my code is more or less correct. I use strict: true and rarely run into problems, especially because I can just use as in the uncommon cases that I can't convince the TypeScript compiler of something.