KodeZnippets
6 days ago
Intro to TypeScript
JavaScript with type safety
Introduction
JavaScript is great for both front-end and back-end. We can leverage the power of JavaScript using TypeScript by typing our code strictly.
What is TypeScript?
TypeScript is a library which allows us to write type safe JavaScript code.
Example 1
The above example enforces the function to return only string
Example 2
The above example enforces the function to return only number and accept only numbers as arguments
Everything seems pretty fine till now. Let's tweak the above code.
Example 2: Failure Case
Here, When we pass string in JavaScript everything will be fine in both compile time and run time, gives undesirable results. But, TypeScript will throw an error at compile time, The build will fail till we fix this code.