Skip to content

Commit

Permalink
Use generics for typing nodeListForEach
Browse files Browse the repository at this point in the history
This allows to forward the type of the `NodeListOf` it iterates on to the parameters of the callback.
In turn this should allow to drop quite a few `instanceof` checks when using the function by properly typing the `NodeList` we give it.

Interesting links:
- [The `@template` JSDoc tag](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#template)
- [How to constrain the generic type](https://stackoverflow.com/a/54631901)
  • Loading branch information
romaricpascal authored and colinrotherham committed Jan 11, 2023
1 parent 89f6ee6 commit 09c6ab5
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/govuk/common/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
* This seems to fail in IE8, requires more investigation.
* See: https://github.com/imagitama/nodelist-foreach-polyfill
*
* @param {NodeListOf<Element>} nodes - NodeList from querySelectorAll()
* @param {nodeListIterator} callback - Callback function to run for each node
* @template {Node} ElementType
* @param {NodeListOf<ElementType>} nodes - NodeList from querySelectorAll()
* @param {nodeListIterator<ElementType>} callback - Callback function to run for each node
* @returns {void}
*/
export function nodeListForEach (nodes, callback) {
Expand Down Expand Up @@ -161,9 +162,10 @@ export function extractConfigByNamespace (configObject, namespace) {
}

/**
* @template {Node} ElementType
* @callback nodeListIterator
* @param {Element} value - The current node being iterated on
* @param {ElementType} value - The current node being iterated on
* @param {number} index - The current index in the iteration
* @param {NodeListOf<Element>} nodes - NodeList from querySelectorAll()
* @param {NodeListOf<ElementType>} nodes - NodeList from querySelectorAll()
* @returns {void}
*/

0 comments on commit 09c6ab5

Please sign in to comment.