JS Tip of the Day: JavaScript with Types: TypeScript

JavaScript with Types: TypeScript

JavaScript is known as a weakly typed language. It doesn’t do much to enforce your proper usage of types and will often use coercion to change between different types of values when performing certain operations. While this can be very flexible, it can also lead to errors or other unexpected behavior.

TypeScript, a superset of JavaScript developed by Microsoft, set out to change this by adding types and type checking to the language. Because it’s a superset of JavaScript, it looks and functions much in the same way - effectively still being JavaScript - except it also has type additional annotations that help ensure your code is more type safe.

TypeScript types are usually denoted in declarations with the type following the variable name separated by a colon. For example:

// TypeScript
let num:Number = 1;

This creates variable num of the type Number with the initial value of 1. If you attempt to assign something other than a Number value to num, you will get an error from the TypeScript compiler due to a type mismatch.

// TypeScript
let num:Number = 1;
num = 'one'; // Type '"one"' is not assignable to type 'Number'

And don’t worry if this looks tedious. Type inference in TypeScript means you often don’t even have to specify the types yourself. They can be implied automatically.

// still TypeScript
let num = 1; // <- implied Number type because 1 is a Number
num = 'one'; // Type '"one"' is not assignable to type 'Number'

TypeScript has been around since 2012 and has steadily been climbing in popularity since then. Even popular frameworks like Angular fully embrace it. If you’re not interested in using it in your own projects, its at least good to know what it is and what it looks like (though we have only just barely scratched the surface here). Chances are you’ll run into it at some point in the future if you haven’t already.

More info: