I'm working on a function that has 1 argument. The argument is either an object (could be nested) or an array of objects. The input can look something like
{
key1: {
key2: [{
key3: 1,
key4: {
key5: [...]
}
}]
}
}
or
[
{ key1: 1, key2: 2, key3: { key4: 'val' }},
{ key5: { key6: { key7: 'val' }}}
]
Any part of the input can be an object or array.
For simplicity's sake, this function takes all the keys of the object, and append New to them.
For example, with input
{
name: 'Name',
email: '[email protected]'
}
Output would be
{
nameNew: 'Name',
emailNew: '[email protected]'
}
If the argument is an array, the function will map through the array and do the same thing.
The issue I'm having is because I don't know the level of nesting for the object, a recursive function is used. Here is what I have so far. Link to playground
interface Object {
[key: string]: Object | Object[];
}
function mapper(arg: Object[]): Object[];
function mapper(arg: Object): Object {
if (Array.isArray(arg)) {
return arg.map(mapper);
}
let result: Object = {};
Object.keys(arg).forEach((key) => {
let newKey: string = key + "New";
let value = arg[key];
if (value instanceof Array) {
result[newKey] = value.map(mapper);
} else if (Object.prototype.toString.call(arg) === "[object Object]") {
result[newKey] = mapper(value);
} else {
result[newKey] = value;
}
});
return result;
}
The issue is with this code
if (Array.isArray(arg)) {
return arg.map(mapper);
}
I do a type check of an array, so I would only go into the block if the input is Object[]. When I map through the input and call mapper on each element, Typescript is using the signature
function mapper(arg: Object[]): Object[]
when each element is an Object. and I get this error
Type 'Object[][]' is not assignable to type 'Object'.
Index signature is missing in type 'Object[][]'.
There are a couple of typing issues, but this is the main one I'm not able to solve.
I'd think Typescript can infer the typing correctly because mapper is called with Object in the map function.