Skip to main content

Type Coercion

Type coercion follows a strict and predictable set of rules to ensure safe and deterministic behavior. Implicit conversions occur only when moving from a lower-precision or less expressive type to a higher-precision or more expressive type, following this priority order:

  1. booleanuint
  2. uintint
  3. intdouble

⚠️ Any other implicit type conversion will result in a runtime error.

Valid Coercions

const a = true + 1;   // true coerced to 1, result is 2 (int)
const b = 10U + 5; // uint coerced to int, result is 15 (int)
const c = b + 2.5; // int coerced to double, result is 17.5 (double)

Invalid Coercions

const x = "10" + 5;   // Error: string cannot be implicitly converted to number
const y = [1, 2] + "hello"; // Error: an array cannot be implicitly converted to a string (what does this mean anyway!!!).

Rationale Behind Coercion Rules

The coercion model is designed to:

  • Ensure type safety by disallowing unpredictable implicit conversions.
  • Avoid silent errors that commonly occur in languages with aggressive coercion (e.g., JavaScript's "5" - 3 producing 2).
  • Allow natural arithmetic operations while maintaining clear type progression.

For conversions outside the allowed hierarchy, explicit type casting is required to enforce clarity in the code.