Conditional never for Key Remapping
You'll learn how to use never in mapped type as clauses to conditionally exclude keys from the resulting type based on custom logic.
The Core Idea
When you're remapping keys in a mapped type using as, you can insert a conditional type that evaluates to never for keys you want to exclude from the output. Since properties can't have the type never as their key name, TypeScript simply drops them from the resulting type.
Think of it like a filter at a security checkpoint: when you check someone's credentials (the property type or name) and they don't meet your criteria, you return never — which is like saying "this person doesn't exist, let them pass through invisibly." The key disappears from the final type.
How It Works
The pattern looks like this:
type FilteredType<T> = {
[K in keyof T as SomeCondition ? never : K]: T[K]
}
The as clause checks a condition. If it's true, you return never, and that key is removed from the result. If false, you keep the original key K.
Practical Example: Removing Optional Properties
type RemoveOptional<T> = {
[K in keyof T as undefined extends T[K] ? never : K]: T[K]
}
type User = {
id: number
name: string
email?: string
age?: number
}
type RequiredUser = RemoveOptional<User>
// Result: { id: number; name: string }
Here, undefined extends T[K] checks if a property accepts undefined (meaning it's optional). If so, return never to drop it.
Another Example: Filtering by Type
type RemoveFunctions<T> = {
[K in keyof T as T[K] extends Function ? never : K]: T[K]
}
type Mixed = {
name: string
age: number
greet: () => void
calculate: (x: number) => number
}
type DataOnly = RemoveFunctions<Mixed>
// Result: { name: string; age: number }
Key Takeaway: Using never in as clauses of mapped types lets you conditionally filter out unwanted properties by key name or value type, giving you precise control over your transformed types.