DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Static vs Dynamic Typing in TypeScript: Key Differences Explained

Static vs Dynamic Typing in TypeScript: Key Differences

Understanding the type system in programming is crucial for writing safer and more maintainable code. Let’s break down the key differences between static and dynamic typing, especially in the context of TypeScript.

Static Typing

  • Types are checked at compile time, before the code is run.
  • Errors related to mismatched types are caught early, during development.
  • TypeScript is a statically typed superset of JavaScript.

Example:

let age: number = 25;
age = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'.
Enter fullscreen mode Exit fullscreen mode

Dynamic Typing

  • Types are checked at runtime, while the code is running.
  • Type errors may only appear when the program is actually executed.
  • JavaScript is a dynamically typed language.

Example:

let age = 25;
age = "twenty-five"; // No error at this point; type changes to string
Enter fullscreen mode Exit fullscreen mode

Why TypeScript Matters

  • TypeScript allows developers to catch type-related bugs during development, reducing runtime errors.
  • You can also opt out of static typing with any, but this removes many of TypeScript’s benefits.

Example:

let value: any = 10;
value = "now I'm a string!"; // No error
Enter fullscreen mode Exit fullscreen mode

In summary:

  • TypeScript: statically typed (checks types at compile time)
  • JavaScript: dynamically typed (checks types at runtime)

Choosing between static and dynamic typing affects code safety, developer productivity, and error detection timing.

Top comments (0)