Consider the code snippet below:
interface ToArraySignature {
(nodeList: NodeList): Array<Node>
(collection: HTMLCollection): Array<Element>
}
const toArray: ToArraySignature = <ToArraySignature>(arrayLike: any) => {
return [].slice.call(arrayLike)
}
toArray(document.body.children).forEach(element => {
console.log(element.scrollTop)
})
The issue here is that toArray always infers the first signature in the interface, causing a compilation error when attempting to access element.scrollTop
as it only exists on the Element type.
To address this, considering an argument of NodeList | HTMLCollection
would compromise the strict relation between input and output.
One solution might be that forcing the signature was not the correct approach. However, how can overloaded functions be implemented without doing so?
Note: This scenario is based on typescript 1.8.10