I need to create a custom implementation of Lodash's _.omit
function using plain TypeScript. The goal is for the omit
function to return an object with specific properties removed, which are specified as parameters after the initial object parameter.
Here is my current 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;
}
This code results in the following error message:
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
Based on this error, I believe:
The variable key is a
keyof T
, and since T is an object, key can be asymbol
,number
, orstring
.When using the
for in
loop, key is restricted to being astring
, while theincludes
method could potentially handle anumber
when passed an array, leading to a type mismatch.
Any suggestions on why this approach is flawed and how it can be rectified would be greatly appreciated!