DEV Community

HichemTech
HichemTech

Posted on

Beyond Type Safety: making TypeScript smarter by Building a Runtime Picker

Disclaimer

Hey, before we get started, let me clarify something: while I’ll be talking a lot about my package, ts-runtime-picker, this isn’t a promotional article. I’m just sharing my experience and the journey I took before building it. (But hey, if you're curious, here's the link to the package 😉).


How TypeScript Led Me to A New Idea (And a Package)

Let’s rewind a bit. So, I’ve been working with TypeScript for a while now. I wouldn’t call myself a TypeScript pro, but I’ve built a few big projects and worked with it at my company. You know, the usual—some “hello world” projects, some slightly more complex ones, and of course, a fair share of trips to Google to figure out “what the heck does this error mean?” or “How do I pick fields from an interface again?” (You get the point. 🙃)

One day, I ran into an issue while working with Firebase cloud functions. I was on the createUser endpoint, writing my validation logic, trimming data, and handling the usual CRUD request madness. Everything was moving smoothly until I ran into this piece of code from a previous developer:

firebase.collection("users").add(request.data.user);
Enter fullscreen mode Exit fullscreen mode

...and my inner TypeScript pro was screaming. 🚨

I mean, come on, this was a massive red flag. Right? Inserting unfiltered user data directly like that was risky—what if the request data was missing some validation and we ended up inserting unwanted fields into the database? Not great.

I quickly removed the code, but then, I froze for a second. 🤔 I stared at my screen thinking: "Hold on, if I just assign request.data to the User interface type, wouldn’t TypeScript stop me from doing something like this? Shouldn’t this fix the issue?" (Cue a hopeful glance at my IDE, waiting for the red squiggly lines to appear.)

But wait… 🤦‍♂️ TypeScript is not magic. It's only a compile-time check, right? It doesn’t exist in runtime. TypeScript is a mask for type safety, but it doesn’t actually enforce anything when the code’s running. It doesn’t really stop extra fields from being inserted at runtime.

So, I called up one of my teammates and asked, “Hey bro, if we have an object named alphabets with all the letters in the alphabet, and we create an interface OnlyTwoLetters that only allows the letters 'a' and 'b', what happens when we cast the alphabets object to that interface?”

// Object with all alphabet letters
const alphabets = {
  a: 'Apple',
  b: 'Banana',
  c: 'Cherry',
  d: 'Date',
  e: 'Eggplant',
  f: 'Fig',
  // ... all the way to z
};

// Interface that only allows 'a' and 'b'
interface OnlyTwoLetters {
  a: string;
  b: string;
}

// Casting alphabets to OnlyTwoLetters
const filteredAlphabets = alphabets as OnlyTwoLetters;

console.log(filteredAlphabets);

Enter fullscreen mode Exit fullscreen mode

Without missing a beat, my teammate said, “Haha, well, you’d still get all the alphabet letters because TypeScript can’t really stop that in runtime.”

Damn. I knew it. I was under the effect of hope—hoping that TypeScript could magically prevent me from making mistakes at runtime. 🙄

But then, it hit me: What if TypeScript could enforce this at runtime? What if we could cast an object to a specific interface and have TypeScript automatically strip out any properties that weren’t defined in the interface?

That would solve my problem.


The Birth of ts-runtime-picker

So, with this lightbulb moment, I thought: “Why not make this a reality?” If I could cast request.data to the User interface, TypeScript could help me automatically remove any extra properties, making the object safe to insert into Firebase. 🎉

And just like that, the idea for ts-runtime-picker was born. The goal was simple: create a package that would allow TypeScript users to filter out unwanted properties from an object, based on the fields defined in a specific interface.

The best part? It would save me from the manual validation and filtering of fields. Gone were the days of:

const filteredData = {
  name: requestData.name,
  age: requestData.age,
};

firebase.collection("users").add(filteredData);  // More work, less fun.
Enter fullscreen mode Exit fullscreen mode

How It Works: Let TypeScript Do Its Job

With ts-runtime-picker, the whole process is automated. You can cast an object to an interface, and the package will ensure that only the properties defined in the interface are kept. Here's how it works in action:

Before: Manual Validation

interface User {
  name: string;
  age: number;
}

const requestData = { name: 'John', age: 30, address: '123 Street' };

// Manually check and remove unwanted fields:
const filteredData = {
  name: requestData.name,
  age: requestData.age,
};

firebase.collection('users').add(filteredData);  // Not very elegant.
Enter fullscreen mode Exit fullscreen mode

After: With ts-runtime-picker

import { createPicker } from "ts-runtime-picker";

interface User {
  name: string;
  age: number;
}

const requestData = { name: 'John', age: 30, address: '123 Street' };

// Automatically filters out non-existent properties:
const picker = createPicker<User>();
const safeData = picker(requestData);

firebase.collection('users').add(safeData);  // Much cleaner!
Enter fullscreen mode Exit fullscreen mode

The best part? This code is safe by default. No need for manual checks or object manipulation. ts-runtime-picker automatically handles it for you by filtering out all fields that don’t exist in the User interface. You can just focus on your core logic without worrying about accidental field insertion. 🙌


The Power of Laziness (and How It Can Lead to Innovation)

So, you might be wondering: "Did this come out of sheer laziness?" And to that, I say: Yes, but also, no. 😅

Sure, the initial spark of the idea came from me being a little lazy—I didn’t want to manually filter fields every time I needed to insert data. But hey, sometimes laziness leads to brilliance! The desire to make things easier can be a driving force for innovation.

In fact, despite the initial “laziness,” I spent 8 hours building the package. Yeah, that’s right. 😆

But that’s how it goes sometimes. "The need gives birth to invention," and this need to avoid tedious repetitive checks led to a new solution that ultimately made my life (and hopefully many others' lives) a lot easier.

So, while I can blame laziness for getting the ball rolling, it was the need to solve the problem that gave rise to ts-runtime-picker. And that’s how sometimes, being stuck or lazy isn’t necessarily a bad thing—it’s the birthplace of something new and useful!


Conclusion

And that’s the story behind the ts-runtime-picker package. A journey from TypeScript frustration to creating a tool that solves a real problem. This package is my way of helping TypeScript users take full advantage of type safety — not just during development but also in runtime.

If you’re tired of manually filtering fields or worried about unwanted data sneaking in, give ts-runtime-picker a shot. It’s one less thing to worry about, and it makes working with TypeScript just a little bit smarter. 😄

Top comments (1)

Collapse
 
petec profile image
PeteC

I wrote a similar function that doesn't use compile-time manipulation of the source. The difference is that you do need to specify an array of field names to copy, but the list is type-checked against the interface that you're copying to.

I think your article is (or should be) more about the power of babble plugins than Typescript per se, since you're not achieving the result purely from using Typescript. It could also do with fewer emojis!