How can the del
function be fixed?
An error is being thrown stating that the type of v
in index(v)
is incorrect:
No overload matches this call.
Overload 1 of 2, '(v: T): number | undefined', gave the following error.
Argument of type 'T | ((v: T) => boolean)' is not assignable to parameter of type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'T | ((v: T) => boolean)'.
Overload 2 of 2, '(op: (v: T) => boolean): number | undefined', gave the following error.
Argument of type 'T | ((v: T) => boolean)' is not assignable to parameter of type '(v: T) => boolean'.
Type 'T' is not assignable to type '(v: T) => boolean'.(2769)
class Enumerable<T> {
index(v: T): number | undefined
index(op: (v: T) => boolean): number | undefined
index(op: T | ((v: T) => boolean)): number | undefined {
return 0
}
}
class Collection<T> extends Enumerable<T> {
del(v: T | ((v: T) => boolean)): void {
const i = this.index(v) // Error
console.log(i)
}
}
new Collection<number>().del(0)
If the distinct declarations of the index
function signature are removed and replaced with a union type, it should work.
// index(v: T): number | undefined
// index(op: (v: T) => boolean): number | undefined
index(op: T | ((v: T) => boolean)): number | undefined {
return 0
}
However, I personally prefer using distinct declarations. The code provided below does not work, but it would if distinct types were used:
class Collection<T> {
order(op?: ((a: T, b: T) => number) | ((v: T) => unknown)): T[] {
return []
}
}
new Collection<[number, number]>()
// Error: Parameter 'pairs' implicitly has an 'any' type.
.order((pairs) => pairs[0])
Is there a better approach to solving this issue?