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

MapValues, MapValuesPick, MapValuesOmit for transformations #195

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

MapValues, MapValuesPick, MapValuesOmit for transformations #195

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?

As a TypeScript developer, I often find myself working with objects and needing to transform the type of their values in a type-safe manner. At times, I want to apply transformations only to specific properties (either by selecting them explicitly or excluding them). Currently, TypeScript does not provide built-in utility types to specifically handle these use-cases.

Describe a solution including usage in code example

Solution:

type MapValues<T, Transform extends (arg: any) => any> = {
    [K in keyof T]: ReturnType<Transform>;
};

type MapValuesPick<T, Keys extends keyof T, Transform extends (arg: any) => any> = {
    [K in keyof T]: K extends Keys ? ReturnType<Transform> : T[K];
};

type MapValuesOmit<T, Keys extends keyof T, Transform extends (arg: any) => any> = {
    [K in keyof T]: K extends Keys ? T[K] : ReturnType<Transform>;
};

Example:

// Transformer function example
const toStringTransformer = <T>(arg: T): string => `${arg}`;


type User = {
    name: string;
    age: number;
    isActive: boolean;
};


type StringifiedUser = MapValues<User, typeof toStringTransformer>;

type PartiallyStringifiedUser = MapValuesPick<User, 'age' | 'isActive', typeof toStringTransformer>;

type MostlyStringifiedUser = MapValuesOmit<User, 'name', typeof toStringTransformer>;

Who does this impact? Who is this for?

This feature would be particularly beneficial for TypeScript developers who work with complex data structures and need a straightforward way to manipulate types across their applications. By reducing the boilerplate associated with types transformations, it could enhance productivity, especially in projects where data manipulation and transformation are frequent operations. This is for developers who prefer maintaining strict type safety while applying transformations or modifications to their types.

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