Reputation: 172
export const omit = <T, U extends keyof T>(obj: T, keys: U[]): Exclude<T, U> =>
Object.keys(obj).reduce(
(acc: any, curr: any) => (keys.includes(curr) ? acc : { ...acc, [curr]: obj[curr] }),
{}
);
Getting an error message stating TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'unknown'.
And would like to have no error messages and a correctly typed function.
Upvotes: 1
Views: 981
Reputation: 1159
It seems to me that you are trying to return an object so I believe you want to return Omit<T, U>
and not Exclude<T, U>
:
You can see the difference here
Here is how you can avoid your errors :
export const omit = <T, U extends keyof T>(obj: T, keys: U[]): Omit<T, U> =>
(Object.keys(obj) as U[]).reduce(
(acc, curr) => (keys.includes(curr) ? acc : { ...acc, [curr]: obj[curr] }),
{} as Omit<T, U>
);
Upvotes: 5