Check out the TypeScript code snippet below. It includes a deeply nested object with various specialKey
keys.
const obj = {
THIS: {
IS: {
MY: {
OBJECT: {
DUDE: {
specialKey: 'foo',
},
specialKey: 'bar',
},
},
},
CANNOT: {
BE: {
specialKey: 'baz',
},
},
},
};
A custom function is utilized to parse this structure and create an object where keys are combined whenever there is a specialKey
.
const result = parseObj(obj);
/*
result = {
THIS_IS_MY_OBJECT: true,
THIS_IS_MY_OBJECT_DUDE: true,
THIS_CANNOT_BE: true,
}
*/
Below is the reference function:
const parseObj = (obj: {}): any => {
const root = {};
const inner = (obj, prefix = ''): void => {
Object.keys(obj).forEach(key => {
if (key === 'specialKey') {
root[prefix] = true;
} else if (key === key.toUpperCase()) {
inner(obj[key], prefix === '' ? key : `${prefix}_${key}`);
}
});
};
inner(obj);
return root;
};
The current code works, but due to its dynamic nature, I am forced to use any
as the return type. This results in no Intellisense for result
. Is there a way to improve the type declaration or modify the function to eliminate the need for any
?