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 Dec 19, 2022
1 parent 0d61b9d commit 1477fce
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 1477fce

Please sign in to comment.