Introduction to TypeScript
By Tejas Shahi ·
TypeScript sounds fancy and intimidating however after stripping away all the hype the answer is actually straight forward.
What is TypeScript?
Type Script is a strongly typed programming language which is developed and actively maintained by Microsoft built on top of JavaScript to solve dynamic type issue in JavaScript and make the code robust and make it easier for developers to find errors early. Any valid JavaScript is also valid TypeScript, The fundamental difference between Standard JavaScript and TypeScript is that it adds static type definitions to JavaScript.
Why do we need TypeScript? - Problem with JavaScript
Standard JavaScripts are dynamically typed which means variable can change types, and it wont complain you until the runtime which does not seems a big issue. But when a wrong kind of data is passed to a function, like passing string where an object is expected results into an unexpected error in JavaScript.
The problem is solved by TypeScript by letting you define what kind of data is expected by the code, this lets developer catch the bugs on runtime.
Example
Plain JavaScript, In JavaScript a typo or type mismatch wont trigger any warning until app runs
function greet(user){
return "Hello, " + user.name;
}// the function expects an object
//passing String instead of object
greet("Alice"); // Returns "Hello, undefined" at runtime with zero warnings!TypeScript, it catches this mistake immediately in code editor
Interface User{
name: string;
age: number;
}
function greet(user: User){
return "Hello, " + user.name;
}
// ❌ TypeScript Compiler Error:
// Argument of type 'string' is not assignable to parameter of type 'User'.
greet("Alice");