I am trying to pass two generic conditions for an array type field name, but the second condition is not being accepted.
This is my method declaration and there doesn't seem to be a problem with it.
firstOrDefault<K extends keyof T>(predicate?: (item: T) => boolean, recursiveItem?: K): T;
The above method declaration is functioning properly. However, I only want to pass an Array type in the recursiveItem field.
I attempted the following method declaration, but it did not work as expected.
firstOrDefault<K extends keyof T & T[]>(predicate?: (item: T) => boolean, recursiveItem?: K): T
Could someone provide guidance on resolving this issue?
Sample Code
let departments : IDepartment[] = [
{
name: 'manager',
subDepartments: [
{
name: 'accountant'
}
]
}
]
// The code snippet above worked, but ideally I want to only pass fields of type T[] such as subDepartments in the recursiveItem parameter.
let department = departments.firstOrDefault(d => d.name == 'accountant', 'subDepartments')
console.log(department)
interface Array<T> {
firstOrDefault<K extends keyof T>(predicate?: (item: T) => boolean, recursiveItem?: K): T;
}
Array.prototype.firstOrDefault = function(this, predicate, recursiveItem) {
if (!predicate)
return this.length ? this[0] : null;
for (var i = 0; i < this.length; i++) {
let item = this[i]
if (predicate(item))
return item
if (recursiveItem) {
let subItems = item[recursiveItem]
if (Array.isArray(subItems)) {
var res = subItems.firstOrDefault(predicate, recursiveItem)
if (res)
return res
}
}
}
return null;
}
interface IDepartment {
name?: string,
subDepartments?: IDepartment[]
}