How To Pick And Omit Keys in TypeScript?
Last Updated :
30 Sep, 2024
In TypeScript, when working with objects, there are scenarios where we may want to pick or omit certain keys from an existing type. TypeScript provides utility types Pick
and Omit
to accomplish this. These utilities allow us to create new types by including or excluding specific properties from an existing type.
Let’s dive into how to use Pick
and Omit
in TypeScript with examples.
What is Pick
in TypeScript?
Pick
Is a utility type that allows us to create a new type by selecting a subset of keys from an existing type. This is useful when we only need certain properties from an object.
Syntax:
Pick<Type, Keys>
Type
: The original type from which properties are picked.Keys
: The specific properties we want to include in the new type.
Example: Let’s say we have a type Person
and we want to pick only name
and age
from it. Here, the BasicPerson type only includes the name and age properties from the Person type.
JavaScript
type Person = {
name: string;
age: number;
email: string;
address: string;
};
// Using Pick to create a new type with only name and age
type BasicPerson = Pick<Person, 'name' | 'age'>;
const person: BasicPerson = {
name: 'Prateek',
age: 20,
};
console.log(person);
// Output: { name: 'Prateek', age: 20}
Output:
{ name: 'Prateek', age: 20 }
What is Omit
In TypeScript?
Omit
is the opposite of Pick
. It creates a new type by excluding specified keys from an existing type. This is useful when we want most properties from a type but need to leave out a few.
Syntax:
Omit<Type, Keys>
Type
: The original type from which properties are omitted.Keys
: The specific properties we want to exclude in the new type.
Example: Let’s omit the email
and address
fields from the Person
type. In this case, ContactPerson will only have the name and age properties from Person, omitting email and address.
JavaScript
type Person = {
name: string;
age: number;
email: string;
address: string;
};
// Using Omit to create a new type excluding email and address
type ContactPerson = Omit<Person, 'email' | 'address'>;
const contactPerson: ContactPerson = {
name: 'Prateek',
age: 20,
};
console.log(contactPerson);
// Output: { name: 'Prateek', age: 20 }
Output:
{ name: 'Prateek', age: 20 }
Combining Pick
and Omit
We can combine Pick
and Omit
to fine-tune the properties we want to include or exclude from an existing type.
Example: Suppose we want to omit the email
the Fromproperty first, and then pick only the name
FromFor the resulting type. In this example, we first omit email using Omit, and then pick only name from the resulting type using Pick.
JavaScript
type Person = {
name: string;
age: number;
email: string;
address: string;
};
// First omit the email field, then pick only the name
type SimplifiedPerson = Pick<Omit<Person, 'email'>, 'name'>;
const simplifiedPerson: SimplifiedPerson = {
name: 'Prateek',
};
console.log(simplifiedPerson);
// Output: { name: 'Prateek' }
Output:
{ name: 'Prateek' }
Nested Picking and Omitting
When working with nested types, we can also use Pick
and Omit
For deeper structures, but we may need to create intermediate types or use type transformations to handle deeply nested fields.
Example: Let’s consider a nested object type where we want to pick certain properties from a nested object. In below code, we omitted the zipCode
field from the nested address
object while retaining the other fields.
JavaScript
type Company = {
name: string;
address: {
city: string;
country: string;
zipCode: string;
};
CEO: string;
};
// Omit zipCode from the address and keep the rest
type SimplifiedCompany = {
name: string;
address: Omit<Company['address'], 'zipCode'>;
CEO: string;
};
const company: SimplifiedCompany = {
name: 'GFG',
address: {
city: 'Delhi',
country: 'India',
},
CEO: 'Prateek',
};
console.log(company);
// Output: { name: 'GFG', address: { city: 'Delhi', country: 'India' }, CEO: 'Prateek' }
Output:
{
name: 'GFG',
address: { city: 'Delhi', country: 'India' },
CEO: 'Prateek'
}
Similar Reads
How to Declare Specific Type of Keys in an Object in TypeScript ?
In TypeScript, object definitions can include specific key-value types using index signatures. You can declare specific types of keys in an object by using different methods as listed below:Table of ContentUsing Mapped TypesUsing InterfaceUsing Inline Mapped Types with typeUsing Record Utility TypeU
3 min read
How to Get an Object Value By Key in TypeScript
In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms o
5 min read
How to Filter Keys of Type string[] in TypeScript ?
In TypeScript, the filtering of keys of type string[] can be done by iterating over the data object, and applying the condition to the string if the key is a string. If the condition is satisfied, then an array of output results is created which consists of filtered keys of type string[]. The below
3 min read
How to Sort or Reduce an Object by Key in TypeScript ?
Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility.Below are the approaches used to sort or redu
3 min read
How to install TypeScript ?
TypeScript is a powerful language that enhances JavaScript by adding static type checking, enabling developers to catch errors during development rather than at runtime. As a strict superset of JavaScript, TypeScript allows you to write plain JavaScript with optional extra features. This guide will
3 min read
How to Make a Single Property Optional in TypeScript ?
TypeScript is a popular programming language that is a strict syntactical superset of JavaScript, adding optional static typing and class-based object-oriented programming to the language. One useful feature of TypeScript is the ability to specify optional properties in interfaces and classes, allow
5 min read
How to parse JSON string in Typescript?
In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a paramet
3 min read
How to Convert Map to JSON in TypeScript ?
In TypeScript, we can convert the Map to JSON by manipulating the key-value pairs of the Map into JSON-formatted string. We can use various approaches like JSON.stringify, fast-json-stringify, and json-stringify-safe Libraries for the conversion.Table of ContentUsing JSON.stringifyUsing fast-json-st
5 min read
How to Create an Object in TypeScript?
TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
How to Deep Merge Two Objects in TypeScript ?
Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore vario
5 min read