I have created a function that is capable of recursively traversing through a nested or non-nested object to search for a specific key and extract its value.
const findName = <T extends object>(obj: T, keyToFind: string): T[] => {
return Object.entries(obj)
.reduce((acc, [key, value]) => {
if(key === keyToFind) {
return acc.concat(value)
} else {
//is the next level of nesting an object so we can keep recursively searching for the key?
if (typeof value === 'object') {
return acc.concat(findName(value, keyToFind)) //problem is here because value is of type any
} else {
return acc
}
}
}, [])
}
I am currently facing an issue where I need to define the type of value
. When calling findName
recursively, I encounter the following error:
No overload matches this call.
Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'any[]' is not assignable to parameter of type 'ConcatArray<never>'.
The types returned by 'slice(...)' are incompatible between these types.
Type 'any[]' is not assignable to type 'never[]'.
Type 'any' is not assignable to type 'never'.
Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'any[]' is not assignable to parameter of type 'ConcatArray<never>'.
I am seeking guidance on how to define a type to resolve this compiler error.
Here is the link to the Playground with the current situation.
Thank you
UPDATE
I have managed to resolve the error by setting reduce's generic to type T[]
, but value
is still tagged as a type of any which is causing linting issues. Is there a way to specify it as a string when concatenating?
const findName = <T extends object>(obj: T, keyToFind: string): T[] => {
return Object.entries(obj)
.reduce<T[]>((acc, [key, value]) => {
if(key === keyToFind) {
return acc.concat(value)
} else {
//is the next level of nesting an object so we can keep recursively searching for the key?
if (typeof value === 'object') {
return acc.concat(findName(value, keyToFind))
} else {
return acc
}
}
}, [])
}