Learning Outcome
What I learnt today
I learnt a bit of typescript as I paired with my Mentor on refactoring a Retirement calculator Kata I had previously written in purely Javascript to use some typescript code.
So what is Typescript?
By definition, “TypeScript is JavaScript for application-scale development.” TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg at Microsoft. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features. (Excerpt Tutorial Point)
Typescript performs static type validation.
So then: Do I need to validate everything? Simply, No
Checking all the variables of my application is time-consuming from a development and performance perspective.
Example:
Here is how my validation test looked like when I writing pure JavaScript
You would notice I am testing by throwing exception for wrong input type ‘string’.
checkout out by blog where I wrote about Don't use exceptions for non-exceptional conditions.
In my constructor function, I wrote a conditional statement that checks if either of currentAge, desiredRetirementAge, or currentYear is of type string, throw an exception with a custom message “Invalid, all inputs must be an Integer“, using the javascript Number.isInteger method
Migrating my logic from Javascript to Typescript, I setup a config file in the root director of my project named tsconfig.json
, this is for managing my project’s options, such as which files I want to include, and what sorts of checking I want to perform.
What my tsconfig.json file.
On Line 7, I am telling typescript to read in any files it understands in the lib
directory (with include
).
I modified my file extension to .ts from .js. At this point, I ran tsc
at the root of my project, I could see output files in the built
directory. The layout of files in built
looks identical to the layout of lib
. I now have TypeScript working with my project.
This is how my constructor logic now looks like after refactoring
First defined the variables and assigned them a type, before passing them as arguments into the constructor function.
Next, I took out the conditional statement, because it is not needed anymore since typescript is already handling validation by ensuring the values for currentAge, desiredRetirementAge and currentAge must all be integers.
I also deleted my test cases, because they really aren’t needed anymore
You can see that giving a string as an argument in my calculator instance, will automatically prompt an error, indicating that this can not run.