Skip to content

Instantly share code, notes, and snippets.

@ediblecode
Last active March 9, 2022 10:44
Show Gist options
  • Save ediblecode/467bc45460b1aa4bf73f45d8c80cbc96 to your computer and use it in GitHub Desktop.
Save ediblecode/467bc45460b1aa4bf73f45d8c80cbc96 to your computer and use it in GitHub Desktop.
Recursively add a property in TypeScript
import { type Primitive } from "type-fest";
export type BuiltIns = Primitive | Date | RegExp;
/**
* Add's a numeric `order` property to all objects within arrays, recursively.
* Used for creating nodes from nested arrays when we want to keep the same order
* as the feed.
*
* Based on type-fest's `ReadonlyDeep`
*
* @see https://github.com/sindresorhus/type-fest/blob/main/source/readonly-deep.d.ts#L37
*/
export type OrderedDeep<O> = O extends BuiltIns | BuiltIns[]
? O
: O extends (infer U)[]
? (OrderedDeep<U> & { order: number })[]
: O extends object
? { [K in keyof O]: OrderedDeep<O[K]> }
: O;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment