


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 is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.