DEV Community

Bilal El Haj
Bilal El Haj

Posted on

Incorporating static types into dynamic

Is it possible to incorporate static types into a dynamic language? The answer is not straightforward; some cases may allow it, while others may prove difficult or even impossible.

The primary obstacle lies in the dynamic features of the language, such as 'eval.' In Python, when you evaluate "1 + eval('2')" it returns 3. However, what happens when you evaluate "1 + eval(read_from_the_network())"? The outcome depends on the runtime input received from the network. If the input is an integer, the expression is acceptable. If the input is a string, the expression is unacceptable. Because the type cannot be determined until the code is executed, it is impossible to statically analyze the type.

The unsatisfactory solution is to assign the type 'Any' to eval(). 'Any' is similar to 'Object' in some object-oriented languages or 'interface {}' in Go, in that it can hold any value. However, values of type 'Any' are not restricted, effectively removing the type system's ability to assist with eval-related code. In languages that have both eval and a type system, type safety is abandoned whenever eval is used.

Some languages have optional or gradual typing, which means they are dynamic by default but allow for the addition of static annotations. Recently, Python has introduced this feature, and TypeScript is a superset of JavaScript that includes optional types. Flow performs static type analysis on regular JavaScript code. These languages provide some benefits of static typing, but they cannot provide the same absolute guarantees as a fully static language. Some functions will be statically typed, while others will be dynamically typed, and programmers must always be aware of and cautious about the differences.

Top comments (0)