Tengo la siguiente función en TypeScript, lo que hace es convertir una enumeración en una matriz.
function toKeyValList(e: any) { return Object.entries(e).reduce((acc: any, val: any[]) => { acc.push({ key: val[0], value: val[1] }); return acc; }, []); } enum IncidentRecordStatus { IN_PROCESS = 'IN_PROCESS', CLOSE = 'CLOSE', } const list = toKeyValList(IncidentRecordStatus); [LOG]: [{ "key": "IN_PROCESS", "value": "IN_PROCESS" }, { "key": "CLOSE", "value": "CLOSE" }]Me gustaría convertirlo en una función genérica sin usar el tipo "cualquiera"
Lo intenté de esta manera, pero me sale un error.
export function toKeyValList<T>(e: T): T { return (Object.entries(e) as Array<[keyof T, T[keyof T]]>).reduce((acc, [key, value]) => { acc.push({ key: key, value: value }); return acc; }, e as T); }cual seria la forma correcta de hacerlo?
No pude entender de dónde viene esa variable LOG , pero aquí está el resto:
interface keyValuePair { key: string, value: string, } function toKeyValList<T extends object>(e: T) : keyValuePair[] { return Object.entries(e).reduce((acc, val : [string, string]) => { acc.push({ key: val[0], value: val[1] }); return acc; }, [] as keyValuePair[]); } enum IncidentRecordStatus { IN_PROCESS = 'IN_PROCESS', CLOSE = 'CLOSE', } const list = toKeyValList(IncidentRecordStatus);Esto devolvería:
[{ "key": "IN_PROCESS", "value": "IN_PROCESS" }, { "key": "CLOSE", "value": "CLOSE" }]Si desea inferir el tipo de devolución, intente evitar las mutaciones en TypeScript. Considere este ejemplo:
const toKeyValList = < Obj extends Record<string, string> >(obj: Obj) => Object .entries(obj) .reduce<{ key: string, value: string }[]>( (acc, [key, value]) => [...acc, { key, value }], [] ); enum IncidentRecordStatus { IN_PROCESS = 'IN_PROCESS', CLOSE = 'CLOSE', } // { // key: string; // value: string; // }[] const list = toKeyValList(IncidentRecordStatus);Ver mi artículo sobre mutaciones TS