Type Coercion
Type coercion follows a strict and predictable set of rules to ensure safe and deterministic behavior. It is designed to maintain type safety by preventing unpredictable implicit conversions. It avoids the kinds of silent errors seen in languages with aggressive coercion—for example, JavaScript allowing "5" - 3
to produce 2
. At the same time, it supports natural arithmetic operations while keeping type behavior clear and consistent.
For conversions outside the allowed hierarchy, explicit type casting is required to enforce clarity in the code.
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:
⚠️ 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!!!).