Why TypeScript
Javascript is a dynamically type language, that is Javascript engine does not check the type of the variable before executing the code. Even a Simple typo error can be discovered only during the run time. Below are some of the runtime behaviour of Javascript when it encounters a error scenario.
a. Incompatible types: As per the code attached below, we are getting a TypeError when we are executing the flip method but getting an output while executing the toLowerCase method.
The above scenario will look obvious for a seasoned Javascript programmer, as “message” variable holds a “string” type and it does not contains any method named “flip” and hence the Javascript runtime engine found that as non sensical and throwed an error TypeError during runtime.
b. Non Existing Method: As per the below code, we are trying to access a method that is not associated with the “person” object, then the JS Engine will throw a TypeError.
c. Mutating an Immutable value: As per the below code, we are trying to change the value assigned to a constant variable and it results in a TypeError.
The above scenarios are commonly known as TypeError and it is thrown at runtime. As per the MDN documentation a TypeError is defined as “The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type
Get sam rubin’s stories in your inbox
Join Medium for free to get updates from this writer.
A TypeError may be thrown when:
- an operand or argument passed to a function is incompatible with the type expected by that operator or function; or
- when attempting to modify a value that cannot be changed; or
- when attempting to use a value in an inappropriate way.”
d. Accessing Non-Existing Function/Variable: If we are trying to access a function and an referring undeclared variable on RHS a ReferenceError will be thrown. For example: As per the below scenario we are trying to access a nonexisting function “fu” Reference Error is thrown.
As per the MDN documentation, Reference Error is defined as “The ReferenceError object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.”
Why TypeScript ?
As we have seen till now JS has two main runtime errors, they are TypeError and ReferenceError. These Error happens at the runtime as the JSEngine checks them during the runtime. TypeScript is a static type checker and it mainly helps in finding all these runtime errors by having a wrapper compilation phase. Let’s explore how TypeScript help in the above scenarios in the next article.








