TAGS :Viewed: 15 - Published at: a few seconds ago

[ How best for an old timer to manage type safety in Javascript ]

I've been writing C/C++/C# for decades, and have used JavaScript as needed for web projects, but want to expand that and do some more in-depth development with Canvas and JavaScript.

My concern is how easily you can make mistakes like setinterval() instead of setInterval(), for example. I'm using VisualStudio and have Telerik's JustCode plugin that does some static analysis, but there's so much that it doesn't check.

I also worry about calling object methods or properties that just don't exist. I understand why these things empower the language and developer with greater flexibility, but how do I best protect myself from the unintended consequences of that flexibility?

Answer 1


I struggled with JavaScript's dynamically-typed nature for a long time too. It turned out to be quite liberating when I finally made peace with it. Here's the mantra that has worked for me:

Program correctness is the most important thing. If I am confident my program exhibits the correct behavior, either my types are correct, or any existing typing errors don't effect program behavior.

This shift in thinking puts more of an emphasis on testing -- which is a good thing. If your tests are well-written, and comprehensive, then type errors will be caught.

I also tend to employ much more of a functional paradigm in my JavaScript coding: if you are not mutating state, strong typing has less meaning.

Of course if you really feel that strong typing is important, there is always TypeScript, which compiles directly to JavaScript and is, by all accounts, an excellent language.

Answer 2


Good design is the answer. Just because it's Javascript and it gives you a lot of freedom doesn't mean the principles you've used until now are any less valid. Design by interfaces (or even better, by contract), make class diagrams, put pen to paper, etc. Do be careful about Javascript's very own brand of object-orientedness, learn about it and the associated patterns (SO has many questions about them) and await ES6 Harmony eagerly.

If you want an IDE, or at least an environment, that tells you what's wrong in a readable and easy-to-use fashion, I recommend simply using your favorite browser's console (your fav browser should be FF or Chrome). Firefox + Firebug is particularly good though, and a favorite among many Web developers. The console, just like in Python, allows you to test snippets of code and to solve your naming errors very fast.

Answer 3


When I finished university I was a promising young lad and was sure that I will have no problems with finding some work. After a while... Bang! The World Economic Crisis struck. So I had to accept some cheap and ugly job and after I fed up with them, I started to search for something better and I risked everything. You might wonder why I am telling all this to you in a semi-scientific site. I am telling you, because through my story you will understand why I am answering the way I am answering. After 3 years of searching for my place and constantly training and educating myself I've got an offer from a small group of programmers, who were using some technologies which were very alien to me. I have joined them and I had to learn many things: .NET framework, Visual Basic, Javascript, jQuery, CSS, Telerik, a lot of libraries. I knew this was my chance to stabilize my position and I was a very trained learner (I have been constantly learning, but in different areas), so I have spent two weeks working 16 hours instead of 8 and at the end I was a constructive member of the team, still a bit rusty in the newly learned languages and technologies, but my results were quite decent. Shortly after that I became used to all the things used there and had no problems.

The thing is that I learned Javascript while learning a lot of other things as well and working in the meantime, having a tight schedule for the tasks. Just like you, I did not like Javascript has no types. I do not like it even now, after all those years. But I had no time to make it more comfortable to me and now I am so used to it that I am too lazy to create something which would help me and the thing would no longer help me.

If you do not want to get used to it the hard way, I believe something like this would help you:

function StrongType(weakValue) {

    //int
    this.i = function() {
        return parseInt(weakValue);
    };

    //float
    this.f = function() {
        return parseFloat(weakValue);
    };

    //string
    this.s = function() {
        return weakValue + "";
    };

    //boolean
    this.b = function() {
        return !!weakValue;
    };

    //change
    this.c = function(newValue) {
        weakValue = newValue;
    };

    //natural
    this.n = function() {
        return weakValue;
    };
}

This would help you to make sure you always know the type you are using. Function names:

You could create a strategy for yourself about how a name is typed and use that for all your functions and variables. If you are using some function and its name is not ok for you, then you can do something like this:

function MyNameHelpers() {
    this.setTimeOut = function(callback, interval) {
        return setTimeout(callback, interval);
    };
}

Also, let's suppose you have a foo object and you want to use its bar member, possibly with parameters:

function MemberUser() {
    this.useMember = function(owner, member, error, errorParams) {
        if (!!owner) {
            return owner[member];
        } else {
            //error is a function to handle the case when owner is falsy
            return error(errorParams);
        }
    };

    this.callMethod = function(owner, member, params, error, errorParams) {
        if (!!owner) {
            return owner[member](params);
        } else {
            //error is a function to handle the case when owner is falsy
            return error(errorParams);
        }
    };
}

The codes above are just illustrations, I did not test/use them, maybe things are needed to be added and so on, but you get the idea. You will either get used to Javascript like I did, or create a library to prevent you from making mistakes. It is your choice.