The Omit type helps you create a new type by leaving out some properties from an existing type. It makes your code cleaner and safer.
0
0
Omit type in Typescript
Introduction
When you want to reuse a type but exclude some fields you don't need.
When you want to create a version of an object without sensitive data like passwords.
When you want to pass an object to a function but prevent certain properties from being included.
Syntax
Typescript
Omit<Type, Keys>
Type is the original type you want to change.
Keys is one or more property names you want to leave out, written as a string or union of strings.
Examples
This creates a new type like
Person but without the age property.Typescript
type Person = {
name: string;
age: number;
location: string;
};
type PersonWithoutAge = Omit<Person, 'age'>;This type excludes the
password property for safer use.Typescript
type FullUser = {
id: number;
username: string;
password: string;
};
type UserWithoutPassword = Omit<FullUser, 'password'>;Sample Program
This program defines a product type and then creates a new type without the description. It then creates an object of the new type and prints it.
Typescript
type Product = {
id: number;
name: string;
price: number;
description: string;
};
// Create a type without description
type ProductSummary = Omit<Product, 'description'>;
const product: ProductSummary = {
id: 1,
name: 'Book',
price: 9.99
};
console.log(product);OutputSuccess
Important Notes
You can omit multiple properties by listing them as a union, like Omit.
Omit is useful to avoid repeating types and to keep your code DRY (Don't Repeat Yourself).
Summary
Omit creates a new type by removing specified properties from an existing type.
It helps you reuse types safely by excluding unwanted fields.
Use it to make your code cleaner and avoid mistakes with object shapes.