Skip to content

Instantly share code, notes, and snippets.

@codepunkt
Created January 17, 2023 20:44
Show Gist options
  • Save codepunkt/e71d9e187b097c1055b95789634ed488 to your computer and use it in GitHub Desktop.
Save codepunkt/e71d9e187b097c1055b95789634ed488 to your computer and use it in GitHub Desktop.
Dual use destructurable
/**
* Creates a return value that is destructurable as both an object and an array.
*
* Usage example:
*
* ```ts
* const obj = createDualUseDestructurable({ foo, bar } as const, [ foo, bar ] as const)
* let { foo, bar } = obj
* let [ foo, bar ] = obj
* ```
*
* @param obj An object
* @param arr An array
* @returns Object that can also be destructured as an array
*/
export function createDualUseDestructurable<
T extends Record<string, unknown>,
A extends readonly any[],
>(obj: T, arr: A): T & A {
const clone = { ...obj }
Object.defineProperty(clone, Symbol.iterator, {
enumerable: false,
value() {
let index = 0
return {
next: () => ({
value: arr[index++],
done: index > arr.length,
}),
}
},
})
return clone as T & A
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment