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 (13)

Collapse
 
ruudt profile image
Ruud Walraven

You ingenuity is much appreciated, I like tinkering and making new things too! The frustrating thing for me though is that there's always someone who thought of my ideas earlier. That doesn't reduce the feat on your end, and there may be users that need a as lightweight as possible solution that need your library. But I do want to point iut Typia. It's capable of much more then just pruning, including checking the correct types of the allowed properties.

import typia from "typia";

type User = {
  name: string;
  age: number;
};

const input = { name: "Anna", age: 24, extra: "remove me" };

const user = typia.misc.assertPrune<User>(input);

console.log(user); // { name: "Anna", age: 24 }
Enter fullscreen mode Exit fullscreen mode

There are some other types of libraries that can also validate unit like Zod, but that isn't really based on TypeScript types.

Collapse
 
hichemtab-tech profile image
HichemTech

Thanks for tips, I'll definitely check them

Collapse
 
kasir-barati profile image
Mohammad Jawad (Kasir) Barati • Edited

Hmm, to me these approaches sound a bit over engineering. I mean yeah we need to sanitize incoming data from our client but that is just about separation of concerns and each layer needs to play its role. When a method/function says I only accept int as input you should not be sending it a string. And if that string comes from user input, someone in the middle needs to sanitize and validate data.

IMO the idea of class-validator, class-trasformer + DTO layer is a very clean architecture for your software.

Do the validation once, not at each layer. Am I forgetting something 🧐?

@ruudt, @hichemtab-tech.

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!

Collapse
 
hichemtab-tech profile image
HichemTech

Thanks for the observation ^.^

Collapse
 
mavrik profile image
ArtemM

I'm curious what happens with nested interfaces? What if my top level interface contains another interface? Does it pick props recursively? What if it is a circular nesting?

A cool idea though. I have so many things in my mind how typescript metadata could improve runtime.

Collapse
 
hichemtab-tech profile image
HichemTech

Well that's a good idea, I didn't think of that, I'll fix it in next version thanks

Collapse
 
deadreyo profile image
Ahmed Atwa

Can you share the logic behind the package?

Collapse
 
hichemtab-tech profile image
HichemTech

Yes ofcs you can check the repository here : ts-runtime-picker - ts-transformer

Collapse
 
namhtpyn profile image
namhtpyn • Edited

You should have mentioned vite some where in this post as this obviously will not work if your project is not using vite.

Collapse
 
ada_e89c9efb7eb2ce2c6c2f3 profile image
Ada

Now what happens if you create a decorator that takes an ordered list of interfaces/classes/types corresponding to the function/method arguments so that you don't have to change function bodies to perform this work?
I'm thinking AOP style validation/input filtering. Should reduce cognitive load on users of the library, and anyone coming in to the code later.
(Something like this would have reduced a massive amount of upcoming effort on my plate)

Collapse
 
huh_hmh_1c5f4812c8caecef7 profile image
Huh Hmh

Much of the same and more propagated type safety can be insured through Typebox

Collapse
 
omril321 profile image
Omri Lavi

Thanks for sharing! As other mentioned, there may be other tools that solve this problem. But I really like your approach and how you learned by solving a real problem 💪

Some comments may only be visible to logged-in visitors. Sign in to view all comments.