utility-types icon indicating copy to clipboard operation
utility-types copied to clipboard

`MapValues`, `MapValuesPick`, `MapValuesOmit` for transformations

Open Antonzo opened this issue 11 months ago • 0 comments

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.

Antonzo avatar Apr 01 '24 14:04 Antonzo