Quick Typescript Sandbox in Emacs

I’ve been working towards mastering JavaScript and TypeScript and have found that deep understanding comes through continuous learning and practice. Despite years of experience, I still find nuances of the language I want to tinker with while quickly visualizing abstract concepts.

Having an actual Typescript buffer with the full power of my editor is the most natural way of turning thought into experiment and feels like such an improvement over tinkering in the Node REPL.

In particular, I have so much muscle memory around Emacs’ compilation workflow that I found myself doing the same few things to get a sandbox up and running for working with Typescript.

So, after creating yet another temporary folder, with a *.ts file, saving the file, and compiling/running this file, I decided to automate this workflow for creating these sandboxes.

My Elisp isn’t great, but for a hacky time-saver, it came together fairly quickly:

(defun bt/create-typescript-sandbox ()
  "Create a temporary Typescript file and set a local variable for
the compile-command."
  (let ((folder (make-temp-file "typescript-sandbox-" t)))
    (find-file (concat folder "/index.ts"))
    (set (make-local-variable 'compile-command) (format "deno run %s" (buffer-file-name)))))

The rough outline of what’s going on:

  • Create a folder in the system’s temporary folder location, for example /tmp/typescript-sandbox-xxxyyyzz
  • Create a file called index.ts within the temporary folder
  • Set the major mode to typescript-mode
  • Set a local variable for the compile command so that it offers to run deno run on the newly created buffer

From there, it’s just a quick call to the function to get a Typescript file that compiles and runs quickly (thanks Deno!)