Last active
March 24, 2022 06:13
-
-
Save noahm/268849b942de8ae6fcbc7845497de961 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ArraysOfEachProperty<T> = { | |
[Property in keyof T]: Array<T[Property]>; | |
} | |
function fieldArrsToObjs<T extends {}>(arrs: ArraysOfEachProperty<T>): Array<T> { | |
const ret: T[] = []; | |
Object.entries(arrs).forEach(([key, values]) => { | |
(values as unknown[]).forEach((value, idx) => { | |
if (!ret[idx]) { | |
// @ts-expect-error | |
ret[idx] = { [key]: value }; | |
} else { | |
// @ts-expect-error | |
ret[idx][key] = value; | |
} | |
}); | |
}); | |
return ret; | |
} | |
/** | |
* Inferred type of legCounts: | |
* Array<{ animal: string, legs: number }> | |
*/ | |
const legCounts = fieldArrsToObjs({ | |
animal: ["dog", "cat", "bird"], | |
legs: [4, 4, 2], | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment