Why TypeScript Enhances JavaScript Reliability
Why TypeScript?
JavaScript Example
- Function Example:
function add(num1, num2) { return num1 + num2; } console.log(add('2', '3'));
- Observation: This JavaScript function adds two numbers, but takes strings as inputs.
- Unwanted Behavior: In JavaScript, using strings with the
+
operator results in concatenation, not arithmetic addition, leading to incorrect results.
Unwanted Behavior at Runtime
- Explanation: Without type checking, JavaScript may execute code that leads to runtime errors or unexpected behavior, such as treating string inputs as numbers.
- Thoughts: Avoiding such errors often requires additional checks, increasing the complexity of the code.
Mitigation Strategies
-
Add if check to add function: Implement runtime checks to verify input types before performing operations.
- Example: Using
typeof
to ensure inputs are numbers. - Thoughts: While effective, this adds overhead and can clutter code.
- Example: Using
-
Validate & sanitize user input: Ensure inputs meet expected criteria before processing.
- Additional Info: Input validation can prevent errors but requires careful implementation.
-
Developers can still write invalid code! : Even with checks, developers may inadvertently introduce errors.
- Observation: Without static type enforcement, runtime errors remain a risk.
TypeScript as a Tool
- TypeScript: A tool that helps developers write more reliable code by introducing static type checking.
- Advantages:
- Immediate Feedback: TypeScript checks types at compile-time, preventing many errors before runtime.
- Improved Readability: Clearer code intentions via explicit types.
- Thoughts: While adopting TypeScript can require extra effort upfront, it leads to more robust and maintainable codebases.
- Advantages:
Extended readings:
hygraph.com
TypeScript vs JavaScript: How are they different? - Hygraph
jaydevs.com
Javascript VS. Typescript: Which Is Better for Your Project In 2023?
www.quora.com
Which one is better: JavaScript or TypeScript? - Quora