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)

  1. 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:

Screenshot 2020-11-19 at 17.12.24.png

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.

Screenshot 2020-11-19 at 16.53.47.png

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.

Screenshot 2020-11-19 at 17.37.25.png

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

Screenshot 2020-11-19 at 17.09.12.png

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.

Screenshot 2020-11-19 at 17.11.31.png

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.

Previous
Previous

Learning Outcome 11th - 18th Dec 2020

Next
Next

Learning Outcome