Skip to content
DevMeme
5843 of 7435
Solving algorithms with TypeScript's type system
Interviews Post #6396, on Nov 20, 2024 in TG

Solving algorithms with TypeScript's type system

Why is this Interviews meme funny?

Level 1: The LEGO Solution

Imagine your teacher gives the class a puzzle to solve and says, "You can show me the answer in any way you want." Most students grab a pencil and write down the answer in words or numbers. But one clever student does something wild: they take a box of LEGO blocks and build the solution as a model. They don't write anything on paper; they just use the LEGO pieces to show the answer. The result is correct – the puzzle is solved – but in a way the teacher never expected. The teacher's jaw drops because they've never seen someone solve a problem like that before. It’s both smart and completely surprising. That’s basically what happened in this story. The interviewer expected a normal answer (some code they could run), but the candidate delivered the solution in a totally unexpected format – using the building blocks of the programming language itself rather than writing out the usual steps. It worked, and it left the interviewer absolutely speechless, just like that teacher staring at a LEGO-built answer.

Level 2: TypeScript’s Hidden Superpower

For a newer developer, this scenario might sound really perplexing, so let's break it down. TypeScript is a programming language often used in web development (especially on the frontend). It’s basically JavaScript with an added layer of static typing. Static typing means you explicitly describe the shapes and types of data in your program (for example, saying a variable is a number or that an object has a field x of type number), and the computer checks those types for errors before running the program. Normally, when you solve a coding problem in TypeScript, you write actual executable code (with variables, loops, functions, etc.), and the type system just runs in the background to catch mistakes.

What happened in this meme is that the candidate decided to solve the problem using only that background type system, instead of writing a normal program. It's as if they used the rules meant for checking code to actually perform the logic of the code. This is highly unorthodox. In a typical interview, when someone says "you can use any language," the expectation is you'll use something like Python, Java, C++ or even TypeScript – but you'll write a regular program that can run and produce output. Here the candidate said TypeScript, but then wrote almost no normal TypeScript code at all. They crafted a series of elaborate type definitions and generic types that, when processed by the TypeScript compiler, would yield the answer. Essentially, they turned the compile-time type checker into a mini-computer for solving the problem. Think of TypeScript’s compiler as a little engine that scrutinizes your code before it's run; this candidate found a way to make that engine solve the puzzle itself during the compile step.

Let's unpack the code snippet to see how this works in practice. The code defines a type called MovePipesImpl with three generic parameters: Pipes, I, and Acc. In simpler terms, you can think of MovePipesImpl as a function (that runs at compile-time) which takes: an array of pipes (Pipes), an index I (a number indicating which pipe it's looking at), and Acc (an accumulator array to collect results). The goal of this "function" is to return a new array of pipes after moving them. Now, normally you'd implement such logic with a loop: start at I = 0, update each pipe, and so on until you reach the end of the array. Here, the code does it with types: Lt<I, Pipes["length"]> is a custom type that checks if I is less than the length of the Pipes array. This acts like the loop condition. If I is less than the number of pipes, the ? ... : ... (ternary conditional) says "we still have a pipe to process." In that case, it does Pipes[I] extends infer P extends Pipe – which is a fancy way in TypeScript to extract the type of the I-th pipe in the array and call it P.

Now the logic splits into two main cases for that pipe P. The line Lte<Add<Sub<P["x"], pipeMoveSpeed>, pipeWidth>, 0> extends true is basically checking: "if P.x - pipeMoveSpeed + pipeWidth <= 0". In plain English, it’s asking: after moving this pipe to the left by pipeMoveSpeed, is the pipe completely off the left side of the screen? (pipeWidth is how wide the pipe is, so if the right edge of the pipe is at or before x = 0, the pipe is off-screen). If the answer is yes (true), that means the current pipe P has moved out of view and we should remove it and add a new pipe on the right side to keep the game going. The code then uses FarthestPipe<0, Pipes, 0, 0> (likely a helper type to find the pipe that’s currently farthest to the right on the screen) and calls it Next. They then construct a new pipe object with { x: Add<Add<Next["x"], pipeWidth>, pipeGap>; y: Sub<Floor<Rand<0, pipeHeight>>, pipeHeight> }. That looks intense, but it's setting up a new pipe’s position: the new pipe’s x is Next.x + pipeWidth + pipeGap (meaning it’s placed just to the right of the current farthest pipe, with a gap so there's space between pipes) and its y is some random height (Rand<0, pipeHeight> suggests they're picking a random number between 0 and pipeHeight, then adjusting it with Floor and Sub to get a proper coordinate). This new pipe is added to the accumulator ([...Acc, { ... }] is how they append to the array in type-land).

If the condition was no (false) – meaning the pipe is still on screen after moving left – then the code goes to the : branch. That part calls MovePipesImpl again (recursively) but this time it adds the current pipe after moving it: { x: Sub<P["x"], pipeMoveSpeed>; y: P["y"] } (reducing the x coordinate by pipeMoveSpeed to shift it left, keeping the same y). It still adds that to the accumulator array ([...Acc, {...}]) and moves on. In both branches, after handling the current pipe, it calls MovePipesImpl<..., Add<I, 1>, ...> – effectively doing I + 1 to proceed to the next pipe in the list. This recursion continues until I is no longer less than Pipes.length. When I equals the length, the check fails and the type resolves to just Acc, which by then is a fully built array of updated pipes. That Acc is of course a type representing the new state of all pipes after one "tick" of movement in the game.

So, step by step, the candidate has built a compile-time equivalent of a loop that updates each pipe and adds a new one if needed, exactly like you would in a normal program for something like the Flappy Bird game (where pipes move across the screen and new pipes appear). But instead of running this logic as code at runtime, they formulated it in the TypeScript type system. The TypeSystemDesign of TypeScript – with features like generics (which let types take parameters like functions), conditional types (which allow if/else logic on types), and recursive types – lets this kind of computation happen during compilation.

For a beginner, it's okay if this feels mind-bending. It really is! This kind of code is not something you encounter in everyday programming. Typically, you'd never need or want to do this – you'd just write normal code and maybe use static types to check it. The candidate basically used TypeScript's type system as a sneaky shortcut to solve the problem in a way nobody expected. Think of it like this: if writing normal code is like writing a recipe for cooking a dish, what the candidate did is more like encoding the recipe in the shopping list of ingredients and having the grocery checker figure out the dish without ever explicitly cooking it. It's a very indirect approach. The interviewer was speechless because they witnessed a correct solution delivered in a format that they'd never seen before. It’s as if you answered a question not by writing an answer, but by cleverly using the question's own rules to reveal the answer. This showcases TypeScript's hidden superpower: its type system is so expressive that, in the hands of an expert, it can solve problems on its own at compile time. But it's also a reminder that just because you can do something in a language doesn't mean that’s the usual or easiest way – sometimes it's done for the wow factor, which is exactly why this story became a popular DeveloperHumor meme among programmers.

Level 3: You Said Any Language...

This meme strikes a chord with experienced developers because it takes an already absurd scenario – the coding interview – and cranks it to 11. The tweet recounts an interview at Facebook where the candidate, when told they could code the solution in any language, calmly replied, "I'll write it in TypeScript types." Imagine an interviewer hearing that. TypeScript is known as a frontend language (essentially JavaScript with a static type layer on top), but writing an entire algorithm using only the type definitions (the part of TypeScript meant for compile-time checks) sounds like a joke. Seasoned devs reading this likely smirked and thought, "Ha, good one." But the punchline is that the candidate did pull it off – the code snippet is proof. It’s pure type-level wizardry: no ordinary variables or loops, just a stack of type aliases and generics performing the logic. The interviewer was left speechless, and it's easy to see why. This was essentially a compile-time mic drop.

From a senior developer's perspective, there's both humor and awe here. Interviews are already high-pressure and unpredictable; we've all heard tales of bizarre technical questions or genius candidates surprising the interviewer. But usually the "genius candidate" might write a brilliantly optimized C++ routine or an elegant one-liner in Python – not an entire solution in a type system. This scenario is off-the-charts InterviewHumor because it subverts the usual script. The interviewer said "use any language," and the candidate took that invitation to an extreme, picking something that's arguably not even a runtime language. It's like exploiting a genie wish loophole in the nerdiest way possible. In the unwritten rules of TechnicalInterviews, you're expected to pick a normal programming language to demonstrate your solution. By using TypeScript's type language, the candidate chose an option the interviewer never saw coming. Honestly, most interviewers wouldn't even know how to execute or verify a solution like this on the spot. The poor interviewer (with the uncannily apt handle @zack_overflow) probably had an internal stack overflow trying to mentally parse those nested <...> generics and conditional extends logic in real-time.

There's also an element of nostalgia and “we've seen something like this before” for veteran devs. It harks back to the era of C++ template metaprogramming, when coding wizards would compute things at compile time just to prove it could be done. Those were often parlor tricks to showcase a language's type system power (and to humble anyone reading the code). What this candidate pulled off is in that same vein, but transplanted to a modern TypeScript codebase. It's both impressive and impractical – clearly a demonstration of skill rather than a maintainable solution you'd use in production. In a real project, no team would want this kind of ultra-clever code in their repository; maintaining it would be a nightmare (imagine debugging a TypeScript compile error that's hundreds of lines long because a type did not line up perfectly!). But as a one-off flex in an interview, it's legendary. This is the kind of story senior devs will be swapping for years: "Remember the candidate who wrote a whole game logic in TypeScript's types?" It also highlights how far frontend engineering has come. A decade ago, front-end developers were mostly writing simple scripts for web pages. Now, thanks to tools like TypeScript, some are so deep into static typing and LanguageFeatures that they can outwit an interviewer with sheer compile-time cleverness.

Finally, consider the human side of this: the interviewer being "speechless" is the comedic cherry on top. Picture that seasoned Facebook engineer, used to grilling candidates on algorithms, now suddenly staring at a wall of angle-bracket hieroglyphics that is apparently the solution to the problem. It's equal parts admiration, confusion, and "What on earth do I do now?" You can bet they hadn't prepped an evaluation rubric for "solved via TypeScript types." In developer culture, we find these moments hilarious and satisfying – when someone flips the script on a common situation in a geekily brilliant way. The reason this meme resonates with so many is that it captures a perfect storm of cleverness: a candidate breaking the norms of the InterviewProcess, an extreme use of a technology we all use (static typing in TypeScript) taken to jaw-dropping heights, and the shared understanding that sometimes the most over-the-top solution can be incredibly entertaining. It's a bit of a cautionary tale ("maybe don't try this in your own interview unless you know exactly what you're doing!") and a celebration of the creativity that makes programming fun. In short, it's both “I can’t believe they actually did that!” and “Wow, that’s one for the books,” rolled into one story.

Level 4: Turing-Complete Sorcery

The TypeScript type system, believe it or not, is powerful enough to act like a full-fledged Turing-complete programming environment. In theoretical computer science, a system is Turing complete if it can simulate any computation given the right instructions. This typically isn't something you'd expect from a language's type checker, yet here we are – the candidate essentially treated TypeScript’s type system as a programming language unto itself. The code snippet MovePipesImpl<...> leverages advanced type-level features (like recursive conditional types, tuple-based arithmetic with Add and Sub, and comparative type logic Lt/Lte) to compute an algorithm entirely at compile-time. Each extends true ? ... : ... in that type alias acts like an if/else in normal code, and the recursion through MovePipesImpl behaves like a loop iterating over the pipes. In effect, the candidate turned the compile stage into a makeshift runtime for their solution. It's a bit of compile-time sorcery: the TypeScript compiler is doing the heavy lifting of calculating new pipe positions purely through type evaluations, with no actual JavaScript executing. This demonstrates a deep understanding of type-level programming – a concept more often found in academic circles or in languages like Haskell, Coq, or Idris, where types can encode complex logic and even proofs.

What's happening in this snippet is reminiscent of C++ template metaprogramming or even the use of dependent types in advanced functional languages. C++ programmers famously showed that you could compute things like Fibonacci numbers or generate lookup tables at compile time using templates – a stunt to prove the compiler's type system was also Turing-complete. TypeScript has quietly joined that club of languages whose type systems are accidentally (or incidentally) as powerful as a general-purpose language. That means you can, in theory, implement any computation using just TypeScript types and generics, though it's usually impractical and mind-bending. In our meme scenario, the interview candidate uses type-level recursion to traverse an array of Pipe objects and determine new positions for each. The presence of a Rand type even hints at generating a pseudo-random number at compile time – which sounds paradoxical, but can be done by clever deterministic tricks (like using template literal types or big union types as a faux-random lookup). Under the hood, the TypeScript compiler must resolve each of these type operations: adding numbers by concatenating tuple types, comparing values by pattern matching on their structure, and so on. It's essentially constructing and reducing types the way a normal program would manipulate data in memory. The theoretical beauty (and absurdity) here is that any logic expressible as type transformations can be evaluated without running a single line of traditional code. This blurs the line between static typing and actual computation: the candidate essentially "proved" the solution via TypeScript's type constraints rather than writing an algorithm in the usual way. It’s a nod to the Curry-Howard correspondence (programs-as-proofs) playing out in a job interview. Of course, doing this pushes the language to its limits – deep recursive types can hit compiler recursion depth caps, and any slight mistake yields errors as cryptic as ancient runes. Yet, the fact that it works in principle showcases the incredible (if esoteric) expressive power lurking in modern type systems. It’s a level of static type wizardry that borders on academia, executed live under interview pressure – no wonder the interviewer was left feeling like they just witnessed a physics-defying magic trick.

Description

This image is a screenshot of a tweet by user 'zack (in SF)' (@zack_overflow), parodying a previous meme format. The tweet reads: 'The most bizarre coding interview I've ever done was at Facebook when as usual I asked a candidate to write in any language of their choice.. And they nonchalantly said "I'll write it in Typescript types", to which I almost let loose a chuckle until...'. Below the text is a snippet of TypeScript code in a dark-themed editor. The code is not typical runtime logic but is instead a complex, recursive type definition named 'MovePipesImpl'. It uses advanced features like generics, conditional types, and the 'infer' keyword, demonstrating type-level programming. The humor comes from the extreme and unexpected application of TypeScript's type system to solve a problem, a flex that demonstrates deep, esoteric knowledge. For senior engineers, it's a nod to the Turing-completeness of modern type systems and the kind of wildly clever, impractical solution that is both horrifying and impressive

Comments

7
Anonymous ★ Top Pick The candidate's code has zero runtime exceptions, zero dependencies, and can calculate the heat death of the universe, but only if the answer is a type
  1. Anonymous ★ Top Pick

    The candidate's code has zero runtime exceptions, zero dependencies, and can calculate the heat death of the universe, but only if the answer is a type

  2. Anonymous

    I got worried when the entire game loop ran in conditional types - ship that to prod and our runtime becomes tsc and our pager is the compiler’s recursion-depth error

  3. Anonymous

    When you've spent so long arguing that TypeScript isn't a real programming language, you accidentally prove it's Turing complete at compile time while trying to make a point

  4. Anonymous

    When the interviewer said 'any language,' they probably weren't expecting a candidate to implement Flappy Bird in TypeScript's type system - a Turing-complete language where the 'runtime' is the compiler and your bugs manifest as 'Type instantiation is excessively deep and possibly infinite.' It's the ultimate power move: writing code that executes during compilation, ensuring your game logic is verified before a single line of JavaScript runs. The real question is whether the candidate's solution passed in O(compile-time) or if the TypeScript compiler needed a coffee break to resolve those nested conditional types

  5. Anonymous

    If your candidate can write Flappy Bird in TypeScript's type system, congrats - you just moved the runtime into the compiler and your latency into tsc

  6. Anonymous

    Nothing like discovering your “any language” policy includes a Turing-complete type system - runtime O(0), compile time O(nested_conditional_types), and tsc is now the VM

  7. Anonymous

    TypeScript at Meta: solving runtime problems at compile time, one infer at a time - until the types themselves need filtering

Use J and K for navigation