type-fest icon indicating copy to clipboard operation
type-fest copied to clipboard

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

Open silversonicaxel opened this issue 1 year ago • 3 comments

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

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

silversonicaxel avatar Jul 28 '23 08:07 silversonicaxel

ConditionalExcept should work:

type B = ConditionalExcept<A, boolean>;

tommy-mitchell avatar Jul 29 '23 01:07 tommy-mitchell

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;
};

silversonicaxel avatar Jul 31 '23 06:07 silversonicaxel

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>;

tommy-mitchell avatar Aug 09 '23 22:08 tommy-mitchell