This article is part of the Series: Typescript utility types, in plain English
Omit in a nutshell ๐ฅ
Very similar to the Pick<Type, Keys>
utility type, Omit
allow you to...
You've guessed it, create a new type by omitting certain keys.
Each key
is delimited by the 'pipe' operator |
type User = {
id: number,
firstName:string,
lastName:string,
email: string,
dob: Date
}
type PublicProfile = Omit<User, 'email'| 'dob'>
/*
Equivalent to
type PublicProfile = {
firstName: string,
lastName:string,
lastName: string,
}
*/
Example โ๏ธ
When should you use Omit
?
- When you want to hide certain properties
The example above is a good example: a User
might want to hide her/his date of birth and email on her/his public profile.
In that case, Omit<Type, Keys>
is the way to go.
- As a way to combine utility types
As you've noticed, Omit
and Pick
are pretty much evil twins.
Omit
does exactly the opposite of Pick
and therefore is also a great 'combinator'.
Omit<Type, Keys>
is also an excellent 'combinator'.
type Post = {
title: string,
subtitle:string,
content: string,
author: User
}
// This is a pretty useless combinator, but I couldn't come up with an example - COVID is taking a toll on my thinking ability ๐คฏ
type AnonymousPostTitle = Pick<Omit<Post, 'author'>, 'title'>
Conclusion โ๏ธ
Omit<Type, Keys>
is simply the opposite of Pick
.
Nothing else to report! ๐๏ธ
When should you use Omit
over Pick
when selecting some properties out of an existing type?
There are no right answers.
Laziness is the key, simply choose the one that is the easiest in the situation.