Many times, when I go speak on modern development, I get asked the same question, “Do I have to use TypeScript?” So I figured I would answer this through a blog post so I can make sure I answer all the pieces to this question. If you haven’t used TypeScript before I’ll cover what TypeScript is and provide the information so you can decide whether you want to use TypeScript in your projects.
- Boolean – true or false value
- Number – any numeric value
- String – any string value
- Array – specifies an array of any other types
- Enumerations – allows definition of custom lists of options
- Any – generic, allows any data
- Void – used in functions to specify that it will not return a value
- Custom Class or Interface – covered later
We’ll cover classes and interfaces in a minute. Included below is a sample of defining a Boolean variable.
In TypeScript “let” is similar to “var” except that “let” variables are scoped to the nearest enclosing block, whereas “var” will be scoped to the nearest function block. The biggest difference is, for example, in if and looping statements if you use “var” the variable scope will be hoisted to the function level while “let” will stay in the scope where it is defined. Consider the example below.
From this we can see the differences of the availability of the different variables based on how they are defined. Also on lines 24 and 25 I am trying to assign values that don’t match the types that were specified and the IDE is notifying us of the problem.
The same sample in TypeScript is a lot simpler:
With TypeScript we get the autocompletion and Intellisense that we are used to using with more powerful tools. We can now take advantage of it in our web front end projects as well.
Another compelling reason is that a lot of major players have adopted it. Why does someone else matter to me? Angular and Microsoft for example are using TypeScript for their new features. With that you will start seeing TypeScript becoming the standard for demos and documentation released by these groups.