Part I. Language as a Computational Model7 min · en inglés

04

Types Checked Later

Since version twenty-three, Node can run TypeScript files without compilation: it cuts out the type declarations and executes what remains. That is enough for a small experiment.

interface Point { x: number; y: number }
function norm(p: Point): number { return Math.hypot(p.x, p.y); }
const fromNetwork: Point = JSON.parse('{"x": "3", "y": null}');
console.log(norm(fromNetwork), typeof fromNetwork.x);

Node 24 prints 3 string. The program declared that x is a number and got a string. Math.hypot silently turned the string into a number and null into zero, and returned an answer that looks very much like the right one. Nobody noticed the error, because there was nobody to notice it. TypeScript, had it been invited, would have checked the text of the program and been satisfied: JSON.parse returns a value of type any, and that may be called whatever you like. The engine would have checked the shape of the object, found fields x and y on it and been satisfied as well. It knows nothing about the numbers in the description of Point, because by the time the program runs, the description has been cut out.


Over thirty years, the question of who checks types in JavaScript has been answered in different ways, and the most instructive of the answers turned out to be wrong. In the early 2000s, real applications were already being written in Flash, and they began to hit speed limits. At Macromedia, as Wirfs-Brock and Eich write citing its engineers, dynamic typing was blamed for the slowness, especially for numbers and strings, and members of the TC39 committee thought the same. Everyone had the same example in front of them: the Java virtual machine, where every variable has a declared type and largely thanks to that everything runs fast. In 2003 ActionScript 2.0 got optional type declarations. They were checked only at compile time and thrown away before the program reached the machine. Macromedia, which Adobe bought in 2005, planned to make types work for speed inside the machine itself as the next step. The fourth edition of ECMAScript, which the committee had been preparing for almost ten years, was supposed to bring classes, packages, namespaces and optional static types into the language, largely modelled on ActionScript 3.

Gratis, solo falta un paso

El resto del libro es gratis

Deja tu correo y te mando un enlace para confirmarlo. Después del clic, todos los capítulos se abren aquí, en este dispositivo, durante un año. Cuando salga un libro nuevo, escribiré a esa dirección; responde “basta” a cualquier correo y no vuelvo a escribir.

¿Tienes cuenta INITE? Entra y el libro se abre sin correo.

No se cobra nada por el libro. Si quieres apoyarlo, puedes donar desde cualquier capítulo.

Cómo se guarda la dirección