How does TypeScript help prevent bugs in JavaScript

JavaScript is an awesome language once you grasp its power and its features. However, like all dynamic languages simple and stupid bugs can creep their way into your code if you are not careful. Many times this happens because types change over type but since JavaScript is dynamic it is really, really hard to detect these changes in an enterprise scale application.

TypeScript helps to solve this problem by providing compile time Type checking. This compile time checking can be used to generate type symbols on your code and alert you, via build errors, when you introduce a simple bug.

Take this code below for example of what I mean

Do you see the error? Look carefully, it is there?

Give up? Image blow has it pointed out

Since I am using KnockoutJs here and trying to set a value on an observable I cannot set the value this way.  I need to set it via method notation.

If we were to add typing to our code as below we would immediately be notified there was an error rather than at run time.


Notice how once I added the typing information to the code the TypeScript compiler was able to tell you that you have a issue in your code, red squigglies and all.

Once we fix our code, as seen below, we are golden.


Now I am not making the claim that TypeScript will fix everything. What I am saying is that by introducing typing into the code and allowing that typing information to flow through your code you will potential to create cleaner and more stable code.

Till next time,

This entry was posted in TypeScript. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Leave a Reply