i need to exclude or pick some fields from an object just like how Pick and Omit works with types so i implemented pick function like below but i had a hard time implementing an exclude function because the ts compiler throw the error No index signature with a parameter of type 'string' was found on type 'Omit<T, keyof T>'
i also tried to search for a solution online but each time i see the result for the Omit type.
here is the pick function works perfectly, a better approach is welcome:
export function pick<T extends Object>(
obj: T,
...s: [keyof T]
): Pick<T, keyof T> {
const returnValue = {} as Pick<T, keyof T>;
s.forEach((k) => {
returnValue[k] = obj[k];
});
return returnValue;
}
exclude function where i got compile errors on line returnValue[e[0]] = obj[e[0]]
i expected this to work fine but seems like i don’t understand something, what i am missing here?
export function exclude<T extends Object>(
obj: T,
...s: [keyof T]
): Omit<T, keyof T> {
const returnValue = {} as Omit<T, keyof T>;
Object.entries(obj).forEach((e) => {
if (!s.includes(e[0] as keyof T))
returnValue[e[0]] = obj[e[0]]
});
return returnValue;
}
i tried looking online for casting string to keyof object but can find nothing.
nidalovski is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.