The typing for Object.entries
provided by typescript has the return type [string, T][]
but I am searching for a generic type Entries<O>
to represent the return value of this function that keeps the relationship between the keys and the values.
Eg. when having an object type like
type Obj = {
a: number,
b: string,
c: number
}
I'm looking for a type Entries<O>
that results in one of the types below (or something similar) when provided with Obj
:
(["a", number] | ["b", string] | ["c", number])[]
[["a", number], ["b", string], ["c", number]]
(["a" | "c", number] | ["b", string])[]
That this isn't correct for all use cases of Object.entries (see here) is no problem for my specific case.
Tried and failed solution:
type Entries<O> = [keyof O, O[keyof O]][]
doesn't work for this as it only preserves the possible keys and values but not the relationship between these as Entries<Obj>
is ["a" | "b" | "c", number | string]
.
type Entry<O, K extends keyof O> = [K, O[K]]
type Entries<O> = Entry<O, keyof O>[]
Here the definition of Entry
works as expected eg. Entry<Obj, "a">
is ["a", number]
but the application of it in the second line with keyof O
as the second type variable leads again to the same result as the first try.