What's the best way to define a type for this specific function? The inputObject should contain all keys from the enablePropertiesArray and may have additional ones. The function is expected to return a copy of the inputObject, inclusive only to the keys mentioned in the enablePropertiesArray.
export const createValidObject = <
T extends string,
IO extends { [K in T]?: unknown } & Record<string, unknown>,
OO = { [K in T]?: IO[K] }
>(
inputObject: IO,
enablePropertiesArray: T[]
): OO => {
let result: { [K in T]?: IO[K] } = {};
enablePropertiesArray.forEach((property: T) => {
if (Object.prototype.hasOwnProperty.call(inputObject, property)) {
result[property] = inputObject[property];
}
});
return result; //Type '{ [K in T]?: IO[K] | undefined; }' is not assignable to type 'OO'. 'OO' could be instantiated with an arbitrary type which could be unrelated to '{ [K in T]?: IO[K] | undefined; }'.(2322)
};
// Tests
const inObject = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key_excess": "value4",
}
const enabledKeys = ['key1', 'key2', 'key3']
const newObj = createValidObject(inObject, enabledKeys)
// newObj = {
// "key1": "value1",
// "key2": "value2",
// "key3": "value3",
// }
// type NewObj = {
// "key1": string,
// "key2": string,
// "key3": string,
// }