Omit by string pattern

Use template literals to omit properties based on a string pattern

L et’s imagine we have an object type that contains development and production keys but we’d like to omit the keys associated with the development environment.

Using the omit utility

We can combine the Omit utility type provided by TypeScript, along with a template literal type to create a new type.

What we are telling TypeScript is to omit all properties from type T that begin with DEV_ followed by any string.

type RemoveKeys<T> = Omit<T, `DEV_${string}`>;
 
type DevRemoved = RemoveKeys<{
  DEV_URL: string;
  STAGING_URL: string;
  PROD_URL: string;
}>;

The result

The result is a new type that omits all properties that begin with DEV_ followed by any string.

type Result = {
  STAGING_URL: string;
  PROD_URL: string;
};

Using string literal unions

You can also provide a union type to the Omit utility type. Imagine we wanted just the production keys.

type RemoveKeys<T> = Omit<T, `DEV_${string}` | `STAGING_${string}`>;
 
type ProdOnly = RemoveKeys<{
  DEV_URL: string;
  STAGING_URL: string;
  PROD_URL: string;
}>;

The result

The result is a new type that omits all properties that begin with DEV_ or STAGING_ followed by any string.

type Result = {
  PROD_URL: string;
};