Skip to content

Instantly share code, notes, and snippets.

@source-c
Last active October 24, 2024 11:00
Show Gist options
  • Save source-c/d9271e8472b894f21e3d15557cc4d979 to your computer and use it in GitHub Desktop.
Save source-c/d9271e8472b894f21e3d15557cc4d979 to your computer and use it in GitHub Desktop.
Typescript Generic Helpers
export const isString = (obj: unknown) =>
obj !== undefined
&& obj !== null
&& (obj instanceof String || typeof obj === 'string');
export const isNone = (v?: unknown): boolean => v === undefined || v === null;
export const isUndefined = (v?: unknown): boolean => v === undefined;
export const isBool = val => 'boolean' === typeof val;
export const asBool = (v?: unknown): boolean =>
isBool(v) ? v :
((isString(v) && v.toLowerCase() === 'true')
|| (Number.isFinite(v) && v > 0));
export const lowerCase = (str: string): string =>
str.toString().toLowerCase()
export const groupBy = <T, K extends keyof any>(arr: T[], key: (i: T) => K) =>
arr.reduce((groups, item) => {
(groups[key(item)] ||= []).push(item);
return groups;
}, {} as Record<K, T[]>);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment