Using Omit in TypeScript
October 23, 2023
Omit 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.
The basic syntax for
Omit is as follows:
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.
Let's say you have a type
If you want to create a new type without the
password field, you'd use
SafeUser will have the shape:
Omitting multiple properties
You can omit multiple properties by providing a union of keys.
This will result in:
Combining with other utility types
Omit can be combined with other TypeScript utility types for more complex operations.
If you want to pick some properties and then omit one from the result, you can combine
The resulting type will be:
- Ensure the keys you provide to
Omitactually 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.
How to fix the "not all code paths return a value" issue in TypeScript
Working with WebSockets in Node.js using TypeScript
Type Annotations Can Only Be Used in TypeScript Files
Guide to TypeScript Recursive Type
How to Configure Knex.js with TypeScript