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

Time:08-14

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

*/

CodePudding user response:

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

  • Related