Sometimes we need to remove a property from a TypeScript Type
or Interface
. For achieving this, since version 3.5, TypeScript provides a utility type called Omit
.
Omit<Type, Keys>
With Omit
, we can construct a type
by picking all properties from a Type
or Interface
and then removing Keys
, which can be a string literal or an union of string literals.
Using Omit"undefined" anchor link
If we want to create a type without a property, we can do it like this:
interface Post { title: string author: string description: string pubDatetime: number}
type PostPreview = Omit<Post, 'description'>
const preview: PostPreview = { title: 'Omit in TypeScript', author: 'Víctor Lillo', pubDatetime: 1615544252770,}
Also, we can remove several properties by using a union of string literals.
interface Post { title: string author: string description: string pubDatetime: number}
type PostContent = Omit<Post, 'author' | 'pubDatetime'>
const content: PostContent = { title: 'Omit in TypeScript', description: 'Remove properties from a type in TypeScript',}
Having the TypeScript Omit
utility type in our repertoire allows us to develope more precise code typing.
Happy coding! 🚀