Hello folks, so in this post, I would be talking about how Typescript saves you from some run-time errors that you might experience in JavaScript by identifying them during compilation time.
Okay so in case you are wondering what exactly is a runtime error or compile-time error let me go ahead and explain it below.
A runtime error is an error that occurs holly holmes steroids when your code is being executed while a compile-time error is an error that is generally known as a syntax error.
An example of a compile-time error can be seen below:-
Typing the code above in your editor would prompt an error message to be displayed because there isn’t a single quote around the word “cat”. So just know that compile-time errors are synonymous to syntax errors.
An example of a runtime error can be seen below: –
In the object above I expected the height method of the record object to return a number. But instead of using a number as an argument, I used a string.
Although the error above looks like it was deliberately made, just bear in mind that errors like this can occur in a real codebase. For instance when you are importing a library or a module and instead of using the correct argument type, you use the wrong one. This error won’t be detected as a compile-time error until you run or execute the code.
Now, this is where Typescript can come in and make bugs like this easy to detect. In JavaScript, you won’t be notified of the error because of how dynamic the language is but in TypeScript the error would be detected if a type or a declaration file is used.
Below is the TypeScript version of the code below:-
With TypeScript the error is being detected with a message telling you the correct type to insert as an argument thereby reducing bugs. TypeScript doesn’t prevent all runtime errors but it really helps to an extent.
Typescript doesn’t only provide type checking feature in JavaScript but also provides extra features like decorators, optional chaining, private and public members in classes and so much more.
If you haven’t started using TypeScript, check It out because it is cool and helps reduce your bugs but you need to have some knowledge of JavaScript to understand it.
The link to TypeScript docs can be found here
Thanks for reading and feel free to comment below if you have any contribution or correction to make.