[Typescript] Understanding Distributive Omit and Pick in TypeScript

We start with three interface types: UserOrganisation, and Product.

These types share common properties: idname, and imageId, but each also possess unique fields. The User type includes ageOrganisation has address, and Product contains price:

type User = {
  id: string;
  name: string;
  age: number;
  imageId: string;
};

type Organisation = {
  id: string;
  name: string;
  address: string;
  imageId: string;
};

type Product = {
  id: string;
  name: string;
  price: number;
  imageId: string;
};

 

And we want to omit `id`:

If we do as such:

type Entity = User | Organisation | Product

type EntityWithoutId = DistributiveOmit<Entity, "id">

We can see a basic object type comprising only of name and imageId, which are the shared properties amongst the three types.

The reason this happens is due to a technicality of how Omit processes union types.

Omit doesn't iterate over every member of the union. Instead, it mushes the union into a structure it comprehends, and then operates on this new construct. As a result, the outcome is different than what you might expect.

 

To remedy this, here's a DistributiveOmit type, which has a similar type definition to Omit, but operates on every member of the union individually.

type DistributiveOmit<T, K extends PropertyKey> = T extends any
  ? Omit<T, K>
  : never;
type DistributivePick<T, K extends PropertyKey> = T extends any
  ? Pick<T, K>
  : never;

When applied to our EntityWithoutId type, we now have a union of the UserOrganisation and Product types without the id field—exactly as initially expected.

type EntityWithoutId = DistributiveOmit<Entity, "id">;

// Hovering over EntityWithoutId shows:
type EntityWithoutId = Omit<User, "id"> | Omit<Organisation, "id"> | Omit<Product, "id">

type test = Expect<
  Equal<
    EntityWithoutId,
    {
      name: string;
      age: number;
      imageId: string;
    } | {
      name: string;
      address: string;
      imageId: string;
    } | {
      name: string;
      price: number;
      imageId: string;
    }
  >
>;

 

posted @ 2024-07-11 14:50  Zhentiw  阅读(1)  评论(0编辑  收藏  举报