Created
March 26, 2020 15:43
-
-
Save PieterScheffers/47a5051953a50d6d4a668586ce8f212a to your computer and use it in GitHub Desktop.
object.entries typescript
This file contains hidden or 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 Entry<T> = [ keyof T, T[keyof T] ] | |
type Entries<T> = Entry<T>[] | |
type Key<T> = (keyof T) | |
type Keys<T> = Key<T>[] | |
type Value<T> = T[keyof T] | |
type Values<T> = Value<T>[] | |
type HasKeys<T> = { [key in keyof T]: any } | |
const keys = <T>(obj: T): Keys<T> => Object.keys(obj) as Keys<T> | |
const toEntries = <T>(obj: T): Entries<T> => Object.entries(obj) as Entries<T> | |
const fromEntries = <T>(entries: Entries<T>): T => Object.fromEntries(entries) as unknown as T | |
const mapObject = <T, U>(obj: T, callback: (entry: Entry<T>) => Entry<U>): U => fromEntries<U>(toEntries(obj).map(callback)) | |
const a: A = { | |
a: 'aaa', | |
b: 'bbb' | |
} | |
const b = toEntries(a).map(([ v, k ]): Entry<A> => [ v, k + '_k' ]) | |
const c = fromEntries<A>(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment