After reaching out to Titian Cernicova-Dragomir on Twitter regarding this matter, it was discovered that despite initial assumptions of no errors, there was in fact a setting causing the issue.
The culprit turned out to be the disabled noImplicitAny
feature in TypeScript. With this option off, TypeScript doesn't rigorously refine variable types implicitly defined as any
, such as in the case of myEcho
. This results in TypeScript not being able to deduce the return value of myEcho("hi")
, allowing the unreported assignment to myInt
. An example demonstrating this behavior with noImplicitAny
disabled can be found here.
Enabling noImplicitAny
(considered best practice) would highlight an error during compilation for the statement myInt = myEcho("hi");
:
Type 'boolean' is not assignable to type 'number'.
A live demonstration showcasing this error can be accessed here.
Despite the presence of an error, the default behavior of the TypeScript compiler is to still generate JavaScript output at runtime if feasible, which explains why you observed the described behavior with myInt
containing a boolean
instead of a
number</code, along with the use of JavaScript's runtime <code>typeof
operator.
To avoid encountering such issues, ensure to check for errors from the TypeScript compiler where type-related errors are typically identified.
If desired, you can also instruct TypeScript to withhold emitting JavaScript when errors are present through the use of the --noEmitOnError
compiler option.