Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get rid of those entries of an TypeScript object type where the values are `never`?

How do I have to implement a type GetRidOfNeverValues<T> that removes all entries of an object type (let’s say: Record<string, any>) where the value is never?

For example

type A = {
  a: number;
  b: string;
  c: never;
};

type B = GetRidOfNeverValues<A>;

/*
  type B shoud now be:

  {
    a: number;
    b: string;
  }

*/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use this technique to create a helper type:

type RemoveValues<T, U> = { [P in keyof T as T[P] extends U ? never : P]: T[P] }

From which we can derive RemoveNever:

type RemoveNever<T> = RemoveValues<T, never>

Or, if you only want the GetRidOfNeverValues type:

type GetRidOfNeverValues<T> = { [P in keyof T as T[P] extends never ? never : P]: T[P] } 
// same as RemoveNever

TS playground link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading