I'm currently working on a function that selectively copies key-value pairs from one object to another in order to remove certain properties. The code snippet for this function is shown below:
sanitizeData: function (sourceObject: object, ...allowedKeys: string[]) {
const sanitizedObject = {};
Object.keys(sourceObject).forEach((key: string) => {
if (allowedKeys.includes(key)) {
sanitizedObject[key] = sourceObject[key];
}
});
}
The purpose of this function is to take an object (e.g., req.body) and a list of strings as input, then perform the specified operation. For instance, an input may look like:
sanitizeData(req.body, 'name', 'age', 'email')
.
This code works seamlessly in JavaScript, however, when trying to run it in TypeScript, I encounter the following error message:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.
If anyone knows how to resolve this TypeScript error, your help would be greatly appreciated.