I want to replicate lodash's _.omit function in plain typescript. omit should return an object with certain properties removed specified via parameters after the object parameter which comes first.
Here is my best attempt:
function omit<T extends object, K extends keyof T>(obj: T, ...keys: K[]): {[k in Exclude<keyof T, K>]: T[k]} {
let ret: any = {};
let key: keyof T;
for (key in obj) {
if (!(keys.includes(key))) {
ret[key] = obj[key];
}
}
return ret;
}
Which gives me this error:
Argument of type 'keyof T' is not assignable to parameter of type 'K'.
Type 'string | number | symbol' is not assignable to type 'K'.
Type 'string' is not assignable to type 'K'.ts(2345)
let key: keyof T
My interpretation of the error is that:
Since key is a
keyof TandTis an object, key can be asymbol,numberorstring.Since I use the
for inloop, key can only be astringbutincludesmight take anumberif I pass in an array, for example? I think. So that means there's a type error here?
Any insights as to why this doesn't work and how to make it work are appreciated!