Omit<Type, Keys> and Pick<Type, Keys>

Stefan Alfbo - Jul 3 '23 - - Dev Community

Are these utility types in TypeScript friend or foe?

Here are some examples of these types from typescriptlang.org


// Pick<Type, Keys>
interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

// Omit<Type, Keys>
interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}

type TodoPreview = Omit<Todo, "description">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};
Enter fullscreen mode Exit fullscreen mode

They look very neat in a small example or in a well constrained domain context. And hey, there is less code to write.

However I have maintained a code base where these utility types has been overused and I'm therefore skeptical to them at this moment. The main problem is for me is that they are making the code less readable and therefore the code is less maintainable. It is also not obvious when changing a "parent" type what consequences that will cause elsewhere in the code. Then there is that feeling of OOP inheritance when using them.

My conclusion right now is to avoid these types when creating the domain model for an application and there has to be a very good reason to add them in my code, but I'm open to change my opinion! Someone has taken the time and effort and added them to TypeScript, and it's probably a good reason behind it (but not clear to me why though).

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .