From 005c78e1368969987956c26350dedf07337495c2 Mon Sep 17 00:00:00 2001 From: Yuzu Date: Wed, 8 Jun 2022 16:27:26 +0000 Subject: [PATCH] Dedicated types (#2268) * feat: dedicated types * patch: AnythingBut with arrays * patch: nested objects stuff * patch: stuff * fix: requested changes Co-authored-by: Skillz4Killz <23035000+Skillz4Killz@users.noreply.github.com> --- types/shared.ts | 83 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 61 insertions(+), 22 deletions(-) diff --git a/types/shared.ts b/types/shared.ts index e289e07e1..4dfc709e4 100644 --- a/types/shared.ts +++ b/types/shared.ts @@ -1356,10 +1356,50 @@ export type Camelize = { : never; }; +/** Non object primitives */ +export type Primitive = + | string + | number + | symbol + | bigint + | boolean + | undefined + | null; +// | object <- don't make object a primitive + +/** + * alternative to 'object' or '{}' + * @example: + * export const o: ObjectLiteral = [] as object; // error + * export const o: object = []; // no error + */ +export type ObjectLiteral = { + [K in PropertyKey]: T; +}; + +/** Array with no utilty methods, aka Object.create(null) */ +export type ArrayWithNoPrototype = { + [index:number]: T | ArrayWithNoPrototype; +}; + +/** + * Allows any type but T + * it is recursive + * @example + * export type RequestData = Record>; + */ +export type AnythingBut = Exclude; +} | ArrayWithNoPrototype; +}>, T>; + +/** + * object identity type + */ export type Id = T extends infer U ? { - [K in keyof U]: U[K]; -} - : never; + [K in keyof U]: U[K]; +} : never; export type KeysWithUndefined = { [K in keyof T]-?: undefined extends T[K] ? K @@ -1367,25 +1407,24 @@ export type KeysWithUndefined = { : never; }[keyof T]; -export type Optionalize = - // Collections don't need optionalizing - T extends Collection ? T - : // If an array only optionalize objects in arrays - T extends unknown[] ? T[number] extends Record ? Array> - : T - : // Specific optionalizing of {} go here - T extends object ? Id< - & { - [K in KeysWithUndefined]?: T[K] extends Collection ? T[K] : Optionalize; - } - & { - [K in Exclude>]: T[K] extends object ? {} extends Pick ? T[K] - : T[K] extends Collection ? T[K] - : T[K] extends unknown[] ? T[K] - : Optionalize - : T[K]; - } - > +type OptionalizeAux = Id<{ + [K in KeysWithUndefined]?: Optionalize; +} & { + [K in Exclude>]: T[K] extends ObjectLiteral ? Optionalize : T[K]; +}>; + +/** + * Makes all of properties in T optional when they're null | undefined + * it is recursive + */ +export type Optionalize = T extends object + ? T extends Array + ? number extends T["length"] + ? T[number] extends object + ? Array> + : T + : Partial + : OptionalizeAux : T; export type PickPartial =