2019-10-18
|~2 min read
|394 words
I’ve written in the past about the benefits of Pick
in writing better interfaces with Typescript.
Today, I found out about Pick
’s mirror: Omit
.1
Quick refresher: Pick
is useful for maintaining the type checking when we only want a select number of properties from an existing interface (as opposed to Partial
). Omit
behaves similarly, but in the inverse: we use it where we want to keep all, but a select number of properties from an interface.
I think of both Pick
and Omit
similarly to extends
in so far as they’re building upon some base. You can think of them similarly to recipes:
Extends
uses all of the ingredients in the original recipe and then adds some more.Pick
takes all of the original ingredients and plucks a few out for use in a smaller dish.Omit
takes all of the original ingredients, but sets aside some of the more specific ingredients because someone in the party is “allergic” to cilantro.Omit
To show how Omit
works, let’s use the same example we’ve used in the past, IMyTable
interface IMyTable {
id: string
foreign_id: string
name: string
is_enabled: boolean
is_custom: boolean
display_order?: number
name_en: string
name_sp?: string
name_fr?: string
description_en?: string
description_sp?: string
description_fr?: string
}
Let’s say that we want to omit the foreign_id
. The type is:
type NewTableProps = Omit<IMyTable, "foreign_id">
This is saying that we will have access to all of IMyTable
except "foriegn_id”
.
Similarly, if we wanted to exclude multiple properties, we use the |
:
type NewTableProps = Omit<IMyTable, "foreign_id" | "is_custom">
Just like Pick
is useful when you want to keep the benefits of type checking and increase the specificity of the interface when all you need is a few attributes, Omit
serves a similar role when you want to exclude a few.
I found this particularly useful when dealing with intrinsic HTML elements with hundreds of properties. Instead of listing out which ones I want to keep, I can simply omit the ones I don’t. For example, Omit<JSX.IntrinsicElements['button'], 'css'>
.
Omit
. I did, however, find this post on Omit And Projection Types by Tomas Brambora useful for understanding how to use Omit
.Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!