TypeScript vs JavaScript: How TypeScript's Type System Prevents Runtime Errors

Learn how TypeScript’s type system helps catch errors early compared to JavaScript, making your code more reliable and easier to maintain.

JavaScript is a versatile and widely-used language, but it is dynamically typed. This means types are checked only at runtime, sometimes causing unexpected errors when the code executes. TypeScript, on the other hand, is a superset of JavaScript that adds static typing. It checks for type errors during development, helping you catch mistakes before you even run your program.

Let's see an example in JavaScript. Imagine you have a function that adds two numbers:

typescript
function add(a, b) {
  return a + b;
}

console.log(add(10, 20)); // 30
console.log(add('10', 20)); // '1020' (unexpected string concatenation)

Notice that in JavaScript, if you accidentally pass a string for the first argument, instead of adding numbers, it concatenates the string and the number. This might lead to bugs that only show when you run the code.

Now, let's write the same function using TypeScript:

typescript
function add(a: number, b: number): number {
  return a + b;
}

console.log(add(10, 20)); // 30
// console.log(add('10', 20)); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

Here, we've declared that the function parameters "a" and "b" must be numbers, and the return value is also a number. If you try to pass a string, the TypeScript compiler immediately raises an error before the code runs. This prevents unexpected behavior and helps you fix mistakes early.

TypeScript’s type system supports many types, such as strings, numbers, booleans, arrays, and even custom types. This system makes your code self-documenting and easier to understand for others (and yourself in the future). It also integrates well with modern editors to provide helpful error messages and autocomplete.

In summary, TypeScript prevents many common JavaScript runtime errors by checking types at compile time. This leads to safer, more predictable code and a better development experience, especially for beginners who want to avoid classic pitfalls.