Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FilterKeys, OmitByCondition, PickByCondition (more flexible variants of Pick and Omit) #194

Open
Antonzo opened this issue Apr 1, 2024 · 0 comments

Comments

@Antonzo
Copy link

Antonzo commented Apr 1, 2024

Is your feature request related to a real problem or use-case?

Sometimes the requirement involves manipulating an object's keys based not strictly on their key types but on other characteristics of the keys, such as key patterns. For these cases Pick or Omit are insufficient.

Describe a solution including usage in code example

Solution:

type FilterKeys<T, Condition> = {
  [K in keyof T]: K extends Condition ? K : never
}[keyof T];

type PickByCondition<T, Condition> = Pick<T, FilterKeys<T, Condition>>;
type OmitByCondition<T, Condition> = Omit<T, FilterKeys<T, Condition>>;

Example:

type AppConfig = {
  dev_databaseUrl: string;
  dev_databaseUser: string;
  prod_databaseUrl: string;
  prod_databaseUser: string;
  common_logLevel: string;
};


type DevelopmentConfig = PickByCondition <AppConfig, `dev_${string}`>;

type NonDevelopmentKeys = OmitByCondition<AppConfig, `dev_${string}`>;

Who does this impact? Who is this for?

For cases where it is important to distinguish between parts of keys, such as prefixes or suffixes. Can be used when key entities differ in some property and therefore there are several variations of keys. As in the example above, key entities are divided into dev and prod (runtime environments).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant