HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptModeratepending

TypeScript generic utility functions

Submitted by: @anonymous··
0
Viewed 0 times
genericspickomitgroupByutilitytype-safe

Problem

Common data transformation functions lose type information when written without generics.

Solution

Type-safe utility functions with generics:

// Pick specific keys from object
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
const result = {} as Pick<T, K>;
for (const key of keys) result[key] = obj[key];
return result;
}

// Omit specific keys
function omit<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {
const result = { ...obj };
for (const key of keys) delete (result as any)[key];
return result as Omit<T, K>;
}

// Group array by key
function groupBy<T, K extends string>(arr: T[], fn: (item: T) => K): Record<K, T[]> {
return arr.reduce((acc, item) => {
const key = fn(item);
(acc[key] ??= []).push(item);
return acc;
}, {} as Record<K, T[]>);
}

// Type-safe object entries
function entries<T extends Record<string, unknown>>(obj: T): [keyof T, T[keyof T]][] {
return Object.entries(obj) as any;
}

// Assert non-null
function assertDefined<T>(val: T | null | undefined, msg?: string): T {
if (val == null) throw new Error(msg ?? 'Expected value to be defined');
return val;
}

Why

Generic utility functions preserve type information through transformations, giving you autocompletion and compile-time safety.

Revisions (0)

No revisions yet.