


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);
...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);
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);
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);
After: With ts-runtime-picker
const filteredData = { name: requestData.name, age: requestData.age, }; firebase.collection("users").add(filteredData); // More work, less fun.
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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
