My TypeScript knowledge led me to create this implementation of a pairs function:
const pairs = <A, B extends keyof A>(a: A): [keyof A, A[B]][] => {
const mapper = (k: keyof A): [keyof A, A[B]] => [k, a[k]]
return Object.keys(a).map(mapper)
}
However, the issue is that it does not maintain valid combinations as expected:
const myPairs = pairs({ a: 1, b: false, c: "a" })
which returns type:
type MyPairs = Array<["a" | "b" | "c", string | number | boolean]>
whereas the correct type should be:
type MyPairs = Array<["a", number] | ["b", boolean] | ["c", string]>
Due to this discrepancy, I am able to manipulate the result in undesirable ways:
myPairs.push(["a", "BUG"]) // This type checks
Is there a way to adjust the pairs
function in TypeScript or FlowType to achieve the desired return type?
--Edit
My editor is displaying issues with the current proposed solution, as shown in this image: