Omit for Database Models Without Computed Fields
What you'll learn: How to use Omit<T, K> to create clean input types by excluding auto-generated or computed properties from your database models.
When working with databases, your model types often include fields that are generated automatically—like id, createdAt, or updatedAt. These fields shouldn't appear in create or update operations because the database handles them. This is where Omit shines.
The Problem
Imagine you have a complete user model representing what comes out of the database:
type User = {
id: string;
email: string;
name: string;
createdAt: Date;
updatedAt: Date;
};
When creating a new user, you only want email and name—the rest are auto-generated. Rewriting the type manually is tedious and error-prone.
The Solution with Omit
Use Omit<T, K> to exclude the computed fields:
type CreateUserInput = Omit<User, 'id' | 'createdAt' | 'updatedAt'>;
// Result: { email: string; name: string; }
Now your create function is type-safe:
function createUser(input: CreateUserInput): User {
// Database generates id, createdAt, updatedAt
return {
...input,
id: 'generated-id',
createdAt: new Date(),
updatedAt: new Date()
};
}
Why This Matters
This pattern prevents mistakes like trying to set an id manually or passing a createdAt value. It keeps your input types aligned with business logic while deriving them from a single source of truth.
Key Takeaway: Use Omit to exclude auto-generated or computed fields from database models, creating accurate input types that prevent invalid operations.