Appearance
Why Use TypeScript?
JavaScript's dynamic typing can lead to several runtime errors that TypeScript helps prevent. Let's look at some examples that demonstrate these problems:
1. Surprising Dynamic Type Behaviour
JavaScript allows variables to change types unexpectedly, which can lead to confusing results:
js
let a = 123;
console.log(a, typeof a); // 123 "number"
a = a + "abc";
console.log(a, typeof a); // "123abc" "string"
// Try with string "100"
let b = "100";
console.log(b, typeof b); // "100" "string"
b = b + 123;
console.log(b, typeof b); // "100123" "string"
// Reverse operation shows the problem
let c = "abc";
console.log(c, typeof c); // "abc" "string"
c = c + 123;
console.log(c, typeof c); // "abc123" "string"
c = c - 123; // NaN
console.log(c, typeof c); // NaN "number"2. Typos in Function Names
JavaScript won't catch typos until runtime, leading to confusing error messages:
js
function add(a, b) {
return a + b;
}
const answer = abb(1, 2); // ReferenceError: abb is not defined
// This error only appears when the code runs!3. Invalid Function Arguments
JavaScript doesn't validate function arguments, which can cause unexpected behaviour:
js
function add(a, b) {
return a + b;
}
const answer1 = add(1, 2, 3); // Just ignores the third argument!
console.log(answer1); // 3
const answer2 = add(1); // Second argument is undefined!
console.log(answer2); // NaN (1 + undefined = NaN)
const answer3 = add(1, "2"); // Second argument is a string!
console.log(answer3); // "12" (string concatenation)4. Unknown Properties
JavaScript creates new properties instead of failing when you make typos:
js
const obj = { a: 1, b: 2 };
obj.aa = 123; // Typo! Now obj = { a: 1, b: 2, aa: 123 }
console.log(obj); // { a: 1, b: 2, aa: 123 }5. Missing Return Values
Functions may unexpectedly return undefined without any warning:
js
function getStateName(id) {
if (id === 1) {
return "idle";
} else if (id === 2) {
return "over";
}
// Missing return for other cases!
}
console.log(`state is ${getStateName(3)}`); // "state is undefined"
// No error, just unexpected undefined!How TypeScript Helps
TypeScript catches these issues during development, leading to more robust and maintainable code. It provides:
- Type safety: Prevents type mismatches and unexpected conversions
- Compile-time errors: Catches typos and invalid function calls before runtime
- Better autocompletion: Helps avoid typos in the first place
- Clearer error messages: More helpful debugging information
TypeScript also catches many other potential bugs, including:
- Uncalled functions: Warns when you forget to call a function
- Unreachable code: Detects code that will never execute
- Unused variables and parameters: Identifies dead code that can be removed
- Switch statement fallthrough: Catches missing
breakstatements that cause unexpected behaviour - Strict null checks: Prevents null/undefined errors that are common in JavaScript
External Resources