DEV Community

Discussion on: Which functions/methods do you...

Collapse
 
mrdulin profile image
official_dulin

utils/ts-utility-types.ts:

export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

export type MaybeNull<T> = T | null;
export type MaybeUndefined<T> = T | undefined;
export type MaybeNil<T> = T | null | undefined;

export type AsyncFn = (...args: any[]) => Promise<any>;
export type AnyFn = (...args: any[]) => any;
export type UnboxPromise<T extends Promise<any>> = T extends Promise<infer U> ? U : never;

export type Nullable<T> = {
  [P in keyof T]: MaybeNull<T[P]>;
};
export type NullableBy<T, K extends keyof T> = Omit<T, K> & Nullable<Pick<T, K>>;

export type DistributedArray<U> = U extends any ? U[] : never;

/**
 * type ID = string | number;
 * type T0 = ID[];
 * type T1 = DistributedArray<ID>;
 * type EQ1 = IfEquals<T0, T1, 'same', 'different'>;  // different
 */
export type IfEquals<T, U, Y = unknown, N = never> = (<G>() => G extends T ? 1 : 2) extends <G>() => G extends U ? 1 : 2 ? Y : N;

export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;

export type ValueOf<T> = T[keyof T];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR 🥇

C'mon show us some functions 🤣🤣

I'm not sure about those TypeDefs honestly, I think it's better to have an inline, let's say:

const foo: string | null = 'whatever';
Enter fullscreen mode Exit fullscreen mode

so it's more clear for everyone than saying

const foo: MaybeNull<string> = 'whatever';
Enter fullscreen mode Exit fullscreen mode

but to keep the honesty in this comment, this is opinionated and I may be wrong 😅