Today, let's talk about a TypeScript feature that's as underrated as a ninja in a library—the in keyword.
🔍 What Is the in Keyword?
In TypeScript, the in keyword isn't just for checking if a property exists in an object. It's a powerful tool for narrowing down types within union types. Think of it as your personal bouncer, ensuring only the right types get past the velvet rope.
🧪 Example 1: Type Guards with in
Imagine you're dealing with a response that could either be a success or an error:
typescript
type SuccessResponse = { data: string; success: true };
type ErrorResponse = { error: string; success: false };
type Response = SuccessResponse | ErrorResponse;
function handleResponse(response: Response) {
if ('data' in response) {
// TypeScript knows 'response' is a SuccessResponse here
console.log('Success:', response.data);
} else {
// TypeScript knows 'response' is an ErrorResponse here
console.error('Error:', response.error);
}
}🛠️ Example 2: Mapped Types with in
The in keyword also shines when creating mapped types. Let's say you have a User type and want to create a new type where all properties are optional:
typescript
type User = { id: number; name: string; email: string };
type PartialUser = { [K in keyof User]?: User[K] };🧩 Example 3: Filtering Properties with in
Need to create a new type by excluding certain properties? The in keyword can help with that too.
typescript
type Circle = { kind: 'circle'; radius: number };
type KindlessCircle = { [K in keyof Circle as Exclude<K, 'kind'>]: Circle[K] };🎯 Why Use the in Keyword?
- Type Safety: It helps TypeScript infer more specific types, reducing runtime errors.
- Code Clarity: Makes your intentions explicit, improving code readability.
- Flexibility: Allows for dynamic type transformations and property exclusions.
