Lies We Tell Ourselves Using TypeScript

Jul 16, 2024

Lies We Tell Ourselves Using TypeScript

Introduction

  • Sadly, the speaker isn't present live but is engaging via chat.
  • Acknowledges the brilliance of previous speakers and sets expectations.
  • Main topic: Discussing the pitfalls and misconceptions of using TypeScript.
  • Speaker's background: Written two books on TypeScript.

Example Code & TypeScript Benefits

  • Example shown: 10-15 lines of code with over 10 hidden errors.
  • TypeScript helps catch subtle bugs that don't cause runtime errors.
  • Main benefit: Prevents hidden errors and makes code more reliable.

The Core Idea: Types & Errors

  • Discusses well-typed TypeScript code that can still throw errors at runtime.
  • Types can provide a false sense of security.
  • Typescript's boundaries are problematic, especially at the I/O level.

Common Pitfalls and Solutions

Problem 1: Fetch and Types

  • Issue: Type assertion with any type is fragile and unreliable.
  • Solution: Use unknown instead of any to force validation.

Problem 2: Error Handling

  • Issue: Catch clauses often assume specific error types when JavaScript can throw anything.
  • Solution: Use unknown in catch clauses and perform specific instance checks.

Problem 3: Function Overloads

  • Issue: Body implementations can return incorrect types not specified in overloads.
  • Solution: Use conditional types to provide a safer, clearer API.

Problem 4: Mutating References

  • Issue: Function mutates objects passed by reference, which TypeScript can't track.
  • Solution: Use generics to enforce type safety when mutating references.

Continuous Problems and More Lies

  • Declaration Merging: Problematic especially when merging with global types accidentally.
  • Instance of Checks: TypeScript's structural type system can cause false positives.
  • Conditional Types: Powerful but overly complex and hard to maintain.
  • Generics: Can still introduce type safety issues if not used correctly.

Why These Problems Persist

  • TypeScript aims to balance productivity and correctness and isn't designed for sound type enforcement.
  • Software engineering is about trade-offs and making decisions, not writing bug-free code.
  • The goal: Awareness of both strengths and limitations of TypeScript to make informed decisions.

Final Thoughts

  • TypeScript makes developers more productive despite its flaws.
  • Emphasis on pragmatism and making informed trade-offs in software development.
  • Encourages understanding of tools and their limitations to make the best decisions for you and your team.
  • Tools are just that—tools to be used wisely.

Thank You

  • Expresses gratitude, encourages questions, and mentions his books for further learning.
  • Final note on being aware of trade-offs and avoiding dogma in software engineering.

Resources

  • Books by the speaker on TypeScript for further reading.