I have this Function
export const ObjectToArray = <T>(object: T): { key: any; value: any }[] =>
Object.entries(object).map(o => ({ key: o[0], value: o[1] }));
I want to remove any
part of result
I even don't know how to start apporach it.
Any hint please
CodePudding user response:
You could use the following approach:
type Entries<T> = {
[P in keyof T]: { key: P; value: T[P] };
}[keyof T];
export const objectToArray = <T>(obj: T): Entries<T>[] =>
Object.entries(obj).map(o => ({ key: o[0] as keyof T, value: o[1] }));
The Entries
generic type simply iterates through the keys of T
, mapping each key into the record you need, to then indexing those keys to create a union of the records.
Inside the objectToArray
function a type assertion is needed because Object.entries
does not preserve the informations about the keys of the input object to avoid some unsound situations.