Using Omit in TypeScript
In TypeScript, Omit
is a utility type that creates a new type by picking all properties from an existing type and then removing specified keys. It's particularly useful when you want to create a type based on another but excluding certain properties.
Let's dive into how you can use this powerful utility in your TypeScript code.
Basic usage
The basic syntax for Omit
is as follows:
type NewType = Omit<OriginalType, KeysToOmit>;
Here, OriginalType
is the type from which you want to omit properties, and KeysToOmit
is a union of keys (as strings) that you want to omit.
Example:
Let's say you have a type User
:
type User = { id: number; name: string; password: string; };
If you want to create a new type without the password
field, you'd use Omit
:
type SafeUser = Omit<User, 'password'>;
Now, SafeUser
will have the shape:
{ id: number; name: string; }
Omitting multiple properties
You can omit multiple properties by providing a union of keys.
Example:
type User = { id: number; name: string; password: string; token: string; }; type SafeUser = Omit<User, 'password' | 'token'>;
This will result in:
{ id: number; name: string; }
Combining with other utility types
Omit
can be combined with other TypeScript utility types for more complex operations.
Example:
If you want to pick some properties and then omit one from the result, you can combine Pick
and Omit
:
type User = { id: number; name: string; password: string; age: number; }; // First, we pick id and password type PickedUser = Pick<User, 'id' | 'password'>; // Now, omit password from the result type IdOnlyUser = Omit<PickedUser, 'password'>;
The resulting type will be:
{ id: number; }
Potential pitfalls
- Ensure the keys you provide to
Omit
actually exist in the original type; TypeScript will not throw an error if they don't. It will simply return the original type unchanged. - When using
Omit
, be wary of potentially losing type information that you may later need.
Invite only
We're building the next generation of data visualization.
How to turn webpages into editable canvases with a JavaScript bookmarklet
Kris Lachance
How to fix the "not all code paths return a value" issue in TypeScript
Kris Lachance
Working with WebSockets in Node.js using TypeScript
Kris Lachance
Type Annotations Can Only Be Used in TypeScript Files
Kris Lachance
Guide to TypeScript Recursive Type
Kris Lachance
How to Configure Knex.js with TypeScript
Kris Lachance