I am facing an issue with my code where I have defined an object with an interface and a utility function to clean up the object by removing undefined properties. However, when I try to pass this object to the utility function, Typescript throws an error.
// utils.ts
// removes undefined props from a generic object
const removeEmpty = (obj: Record<string, unknown>): Record<string, unknown> => {
Object.keys(obj).forEach(key => obj[key] === undefined ? delete obj[key] : {});
return obj;
};
// some api
interface IMyAPIParams {
first: string;
second: string;
extra1?: string;
extra2?: string;
}
const baseReq: IMyAPIParams = {
first: "one",
second: "two",
};
// some code, that may result in some of these extra properties being present
// but with value of 'undefined'
const req = removeEmpty(baseReq);
/**
* 1.
*
* Error: Argument of type 'IMyAPIParams' is not assignable to parameter of type
* 'Record<string, unknown>'.
* Index signature for type 'string' is missing in type 'IMyAPIParams'
*/
/**
* 2.
*
* const req = removeEmpty(baseReq as Record<string, unknown>);
*
* Error: Conversion of type 'IMyAPIParams' to type 'Record<string, unknown>'
* may be a mistake because neither type sufficiently overlaps with
* the other.
* If this was intentional, convert the expression to 'unknown' first.
*/
I need help to resolve this issue in my code without using @ts-ignore. I believe this issue stems from trying to incorporate typical JS code into TypeScript.