FP seeking for-of where Typescript prohibits it

Consider the following code:

const getDisabledFieldsSet = function(form: HTMLFormElement) {
	const disabledFields: Element[] = [];
	//Using for-of to open this loop, e.g.
	//for(let input of form) {
	//fails w/err: Type 'HTMLFormElement' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488)
	//However, Sonar insists on using for-of.
	//Expected a `for-of` loop instead of a `for` loop with this simple iteration.sonarlint(typescript:S4138).
	//It does not appear possible to simultaneously satisfy both checkers.
	for(let i = 0; i < form.length; i++) {
		const input = form[i];
		if(input.hasAttribute('disabled')) {
			disabledFields.push(input);
		}
	}
	return disabledFields;
}

Sonar should not report a TypeScript issue seeking a for-of field in cases where TypeScript prohibits it, even if the prohibition is a TypeScript issue associated with not properly including the “dom.iterable” option in the “lib” compiler option.

Hi,

What product are you seeing this in? SonarCloud, SonarQube or SonarLint? And if either of the latter two, what version?

 
Thx,
Ann

Hi Ann,

Sorry I forgot to include that in my report; I’m seeing this in SonarLint v3.5.4.

Hi Ben,

Thank you for notifying us of this issue. Indeed HTMLFormElement can be accessed through its indices as an array, but it does not have an iterator function which prevents it from using for .. of ...
You can however augment HTMLFormElement using Array.from() like that:

const getDisabledFieldsSet = function(form: HTMLFormElement) {
	const arrayForm = Array.from(form);
	const disabledFields: Element[] = [];
	for(const input of arrayForm) {
		if(input.hasAttribute('disabled')) {
			disabledFields.push(input);
		}
	}
	return disabledFields;
}

Then Sonar’s message requiring use of for...of should explain how you have to add extra lines to the code to convert it into an object type that allows its use, or better yet just drop the false-positive detection.

Thank you for the input, Ben.

I have opened an issue to track this FP: FP S4138: check if node does have an iterator to use for-of · Issue #3385 · SonarSource/SonarJS · GitHub

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.