sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
14.34k stars 545 forks source link

Is it possible to Omit native type like booleans or numbers? #653

Closed silversonicaxel closed 8 months ago

silversonicaxel commented 1 year ago

I would like to know if it is possible to have a scenario like this one:

type A = {
  a: string;
  b: number;
  c: boolean;
  d: boolean;
  e: boolean;
};

type B = Omit<A, boolean>;

where type B looks like this

type B = {
  a: string;
  b: number;
};

Upvote & Fund

Fund with Polar

tommy-mitchell commented 1 year ago

ConditionalExcept should work:

type B = ConditionalExcept<A, boolean>;
silversonicaxel commented 1 year ago

Amazing, last part of question is, what if one boolean is optional? Because now, considering this example:

type A = {
  a: string;
  b: number;
  c: boolean;
  d?: boolean;
  e: boolean;
};

type B = ConditionalExcept <A, boolean>;

type B looks like this:

type B = {
  a: string;
  b: number;
  d?: boolean;
};
tommy-mitchell commented 1 year ago

d?: boolean is the same as d: boolean | undefined (for most cases). One solution is to use the built-in Required utility type (TS Playground):

type B = ConditionalExcept<Required<A>, boolean>;