Home Web Front-end JS Tutorial Beyond Type Safety: making TypeScript smarter by Building a Runtime Picker

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

Dec 16, 2024 pm 08:25 PM

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);
Copy after login
Copy after login

...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);

Copy after login
Copy after login

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:

firebase.collection("users").add(request.data.user);
Copy after login
Copy after login

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

// 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);

Copy after login
Copy after login

After: With ts-runtime-picker

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

firebase.collection("users").add(filteredData);  // More work, less fun.
Copy after login

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. ?

The above is the detailed content of Beyond Type Safety: making TypeScript smarter by Building a Runtime Picker. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles