Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Omit is a utility type in TypeScript that allows excluding specific properties from an already existing type or interface. It creates a new type by removing from original field list those you specified.
Omit<T, K>
T — original type (or interface) from which you want to exclude properties.K — union of keys you want to remove from T.Omit removes named fields and leaves everything else unchanged.
Suppose we have a User interface with several fields:
interface User {
id: number;
name: string;
age: number;
isAdmin: boolean;
}
If in some place of application we want to work with user but don't want to have access to isAdmin, we can use Omit:
type PublicUserData = Omit<User, "isAdmin">;
const userData: PublicUserData = {
id: 1,
name: "Alice",
age: 25,
};
userData.isAdmin = true;
// ❌ Error: property 'isAdmin' is missing in type 'PublicUserData'
PublicUserData — contains all User fields except isAdmin.isAdmin will cause compilation error as this property doesn't exist in new type.Often after getting user data from database or external API you want to pass to "frontend" object without some private fields:
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
isAdmin: boolean;
}
type SafeUserData = Omit<User, "passwordHash" | "email">;
function getSafeUserData(user: User): SafeUserData {
const { passwordHash, email, ...rest } = user;
return rest;
}
const user: User = {
id: 42,
name: "Bob",
email: "bob@example.com",
passwordHash: "hashed_password",
isAdmin: false,
};
const safeData = getSafeUserData(user);
// safeData doesn't contain passwordHash and email
In result only id, name and isAdmin are passed outward, while confidential data remains hidden.
password, token, isAdmin) for public data representation.