What does Omit<T, K> do?
1. What Omit<T, K> does
Omit<T, K>creates a new type based onT, excluding the properties listed inK.
Syntax
Omit<SourceType, 'key1' | 'key2'>Example
interface User {
id: number;
name: string;
email: string;
password: string;
}
type PublicUser = Omit<User, 'password'>;Now PublicUser is equivalent to:
{
id: number;
name: string;
email: string;
}The
passwordfield is excluded from the type.
2. How Omit is the opposite of Pick
| Utility | What it does | Example |
|---|---|---|
Pick<T, K> | keeps only the specified properties | Pick<User, 'id' | 'name'> |
Omit<T, K> | removes the specified properties | Omit<User, 'password'> |
Visually:
interface User {
id: number;
name: string;
email: string;
password: string;
}
// Pick
type MinimalUser = Pick<User, 'id' | 'name'>;
// { id: number; name: string }
// Omit
type SafeUser = Omit<User, 'password'>;
// { id: number; name: string; email: string }That is: Pick = "take what's needed", Omit = "remove what's not".
3. How Omit<T, K> works internally
The language-level implementation of Omit looks like this:
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;What happens:
keyof Ttakes all the keys of the source type.Exclude<keyof T, K>removes from them the ones listed inK.Pick<...>creates a new type based on the remaining properties.
4. Can you remove several properties with Omit
Yes, you can specify several properties at once via a union (|):
type UserWithoutSensitive = Omit<User, 'password' | 'email'>;The result is:
{
id: number;
name: string;
}TypeScript removes all the listed fields from the resulting type.
5. Usage example in real projects
Removing sensitive data
interface Employee {
id: number;
name: string;
email: string;
salary: number;
}
type PublicEmployee = Omit<Employee, 'salary'>;This type is convenient for safely returning data from an API.
Simplified forms
interface FormData {
id: number;
name: string;
createdAt: Date;
updatedAt: Date;
}
type FormInput = Omit<FormData, 'id' | 'createdAt' | 'updatedAt'>;The form only needs the input fields (
name), while the rest are generated automatically.
6. An error for a nonexistent key
If you try to remove a field that does not exist on the type, TypeScript immediately shows an error:
type Wrong = Omit<User, 'nickname'>;
// Error: Type '"nickname"' is not assignable to keyof 'User'That is,
Omitchecks that the specified keys actually exist onT.
Summary
| Question | Answer |
|---|---|
What does Omit<T, K> do | Creates a new type without the specified properties |
How it differs from Pick | Pick selects the needed fields, Omit removes the unwanted ones |
| Can you remove several properties | Yes, via 'prop1' | 'prop2' |
| What happens if you remove a nonexistent one | Error: key not found on the type |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.