Search code examples
typescriptmapped-types

Typescript: How to remove properties of object/mapped type by value


Is there a way to remove some props of an object via a mapped type based on their value? So similar to Omit, but discriminating by value, instead of key.

Given this example:

type Q = {a: number, b: never}

How could I remove b based because it is never.


Solution

  • I found out that you can construct a helper type in similar fashion to Omit like so:

    type RemovePropsByValue<T, V> = {
      [K in keyof T as T[K] extends V ? never : K]: T[K];
    };
    

    Which can be used like so:

    type Q = {a: number, b: never}
    type FilteredQ = RemovePropsByValue<Q, never>; // typeof {a: number}