Public Type
Less than 1 minuteTC-Medium
Public Type
Problem
Remove the key-value pairs that start with an underscore (_) from an object type.
type T = PublicType<{ _name: string; _age: number; email: string }>
// { email: string }Solution
type PublicType<T extends object> = {
[K in keyof T as K extends `_${string}` ? never : K]: T[K]
}How it works:
- Use a mapped type with key remapping (
as). - For each key
K, check if it matches the template literal`_${string}`. - If it starts with
_, remap tonever— which removes the key from the output. - Otherwise keep the key as-is.
Key Takeaways
- Key remapping with
asandneveris the idiomatic way to filter keys in a mapped type. - Template literal pattern
`_${string}`cleanly matches any string starting with an underscore. - This is simpler than using
OmitorPickwith a union of filtered keys.
