Article URL: https://healeycodes.com/adding-defer-to-the-typescript-compiler Comments URL: https://news.ycombinator.com/item?id=49147853 Points: 14 # Comments: 4

I wanted to see how difficult it would be to add Go's defer statement to the TypeScript compiler, but by the time I finished I was convinced it probably shouldn't exist. In Go, the defer statement delays the execution of a function until the surrounding function finishes. It's most commonly used to keep resource acquisition and cleanup together, like acquiring a semaphore: TypeScript doesn't have a strict equivalent of defer. You might use try/finally, like: For fun, we can hack in a defer statement to the TypeScript compiler and get Go-like semantics. Since defer doesn't map to an existing JavaScript feature, we need to output JavaScript code that makes it work at runtime just like it does in Go. The TypeScript compiler (tsc) is mostly a static analysis engine. Its complexity lies in type-checking a fundamentally dynamic language, and supporting extremely incremental compilation to meet latency expectations in an IDE. Lucky for us, we don't need to worry too much about types or other analysis in order to add our defer statement. tsc already has the machinery for "recognize syntax X, replace it with equivalent syntax Y." Conceptually, adding defer means doing another tree rewrite. tsc already performs a number of AST-to-AST transformations (e.g. optional chaining ?. becomes conditional expressions) so we don't need to add new tooling. There's some complexity to dig into, but at a high level, we'll take an AST with defer: