rhondamuse.com

Mastering Property Exclusion in TypeScript for Clean Code

Written on

Chapter 1: Understanding Property Exclusion

As a TypeScript developer, I frequently encounter scenarios where I need to manage types that contain more information than necessary. For instance, I might have a type with ten properties, but my focus is only on five of them.

TypeScript's Omit and Pick Utility Types

The Omit operator serves as a powerful tool for deriving new types from existing ones by removing specified properties. This functionality is invaluable for creating tailored variations of types. Think of it as a selective tool for refining your TypeScript types. For official documentation, refer to the TypeScript site.

1. Basic Example

Consider a type that defines a car:

interface Car {

make: string;

model: string;

year: number;

color: string;

}

If you need a type that includes only the essential car details, excluding the color, Omit comes to the rescue:

type BasicCarInfo = Omit<Car, 'color'>;

let myCar: BasicCarInfo = {

make: "Honda",

model: "Civic",

year: 2022

// Color property is omitted!

};

2. Omit vs. Pick

If you have a more complex User type:

interface User {

userId: number;

name: string;

email: string;

isAdmin: boolean;

}

To present only basic user details, you can use Omit to exclude userId and isAdmin:

type PublicUserInfo = Omit<User, 'userId' | 'isAdmin'>;

Alternatively, you can construct PublicUserInfo by actively selecting the desired properties:

type PublicUserInfo = Pick<User, 'name' | 'email'>;

Both Pick and Omit are used to create new types based on existing ones, where Pick focuses on inclusion and Omit on exclusion.

3. Handling API Responses

When dealing with a large dataset from an API, you might want to filter out unnecessary fields. Here's how you can utilize Omit effectively:

interface APIProduct {

id: number;

name: string;

price: number;

// ... additional fields

}

type ProductSummary = Omit<APIProduct, 'id'>;

TypeScript Utility Types: Exclude - YouTube

This video explains how to use utility types in TypeScript, specifically focusing on the Omit type for excluding unwanted properties.

Chapter 2: Simplifying React Components

Using Omit with React Props

Suppose you have a custom Button component with several props:

import React from 'react';

interface ButtonProps {

onClick: () => void;

label: string;

size: "small" | "medium" | "large";

disabled: boolean;

type: "button" | "submit" | "reset";

}

const Button: React.FC<ButtonProps> = ({ onClick, label, size, disabled, type }) => {

// Button rendering logic

};

Now, if you wish to create a new component, SimpleButton, that accepts only the essential button props (label and onClick), you can leverage Omit:

  1. Extract Props Type: Obtain the props type of your existing component:

type ButtonProps = React.ComponentProps<typeof Button>;

  1. Omit Unneeded Props: Exclude the unnecessary props:

type SimpleButtonProps = Omit<ButtonProps, 'size' | 'disabled' | 'type'>;

  1. Create the Simplified Component:

const SimpleButton: React.FC<SimpleButtonProps> = ({ onClick, label }) => {

// Simple button rendering logic

};

In this scenario, Omit ensures type safety, preventing the inclusion of unused props in the SimpleButton component.

Other Methods for Property Exclusion

  • Destructuring with Rest

Destructuring combined with rest patterns can also help in extracting specific properties while omitting others:

interface Person {

name: string;

age: number;

city: string;

}

const person: Person = { name: "Alice", age: 30, city: "New York" };

const { name, ...rest } = person;

console.log(name); // Output: "Alice"

console.log(rest); // Output: { age: 30, city: "New York" }

In this example, the name property is captured while the remaining properties are collected into the rest object.

  • Manually Defining New Types

Although straightforward, this method is not typically recommended. You can create a new type by listing only the properties you want to include:

interface Book {

title: string;

author: string;

pageCount: number;

}

interface BookSummary {

title: string;

author: string;

}

In this case, BookSummary omits the pageCount property by not including it in the definition.

  • Type Intersection with Never

A more advanced technique involves utilizing type intersections with the never type:

interface Employee {

id: number;

name: string;

role: string;

}

type EmployeeWithoutRole = Employee & { role: never };

Here, we intersect Employee with an object where role is defined as never, effectively removing it from the resulting EmployeeWithoutRole type.

Excluding Values from Literal Types in TypeScript - YouTube

This video dives into the concept of excluding values from literal types in TypeScript, illustrating practical examples.

Enjoyed the read? Show your support with a like! I'm always eager to connect with fellow tech enthusiasts. Feel free to reach out on LinkedIn!

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Three Essential Beverages for Gut and Liver Wellness

Discover three beverages that can enhance gut and liver health, supported by insights from a gastroenterologist.

Windows 11's First Major Update: A Letdown for Users

Windows 11's first major update disappoints with minimal new features and ongoing customization frustrations.

Embracing Support: Why Going Sober Alone is a Challenge

Discover why seeking support is crucial on the journey to sobriety. Learn from personal insights and expert guidance on embracing community.