- Typescript Daily
- Posts
- What's Hidden Behind TypeScript's keyof?
What's Hidden Behind TypeScript's keyof?
A deep dive into the operator that has everyone intrigued.
๐ฏ TypeScript Daily Digest!
Advanced Feature: Harnessing the Power of keyof
Type Operator
Problem Statement:
Picture thisโyou're working with object types every day, creating functions that need to use object keys as parameters. You need your code to be foolproof, ensuring only valid keys of an object can be used. How can you achieve this level of precision and safety?
Use Case:
Imagine you're developing a library to work with user profiles. These profiles are objects with keys like "name", "age", and "location". Your library should allow other developers to retrieve or update values using these keys, but it should catch invalid keys before runtime.
๐ Basic Example: Strongly-Typed Object Property Accessor
Here, getProperty
function is type-safe and accepts only the keys that exist in the specified object type, thanks to keyof
.
๐ Medium Example: Generic Object Updater
Our updateProperty
function is now robustโit ensures that not only the key but also the value passed in is of the right type.
๐ Advanced Example: Dynamic Filters with keyof
With filterByProperty
, you can dynamically filter an array of objects based on a given key and value pair. TypeScript ensures that the key exists on each object and that the value is of the correct type.
Real-World use-cases:
Below are the 10 real-world use cases where keyof helps.
๐ก API Request Parameter Validation:
Use
keyof
to create a type-safe way to validate incoming request parameters against a known model, helping to ensure data integrity before it gets processed or saved.
Reply