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.
Free, one step away
The rest of the book is free
Leave your email and I will send a link to confirm it. Once you click it, every chapter opens here, on this device, for a year. When a new book comes out I will write to this address; reply “stop” to any email and I will not write again.
Have an INITE account? Sign in and the book opens without an email.
I do not charge for the book. If you would like to support it, you can donate from any chapter.
How your email is stored