eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Incorrect `no-for-loop` fix for strings in TypeScript

Open andrmoel opened this issue 8 months ago • 1 comments

Setup:

  • TypeScript
  • eslint + no-for-loop

I use the no-for-loop rule to auto fix my code. My code iterates through a string value. The autofix changes my code wrong and assumes that my string is an object.

Original Code

function renderAnimatedChars(formattedValue: string): void {
    for (let i = 0; i < formattedValue.length; i++) {
        const char = formattedValue[i];

        console.log(`Key: ${i} Value: ${char}`);
    }
}

Code after autofix

    function renderAnimatedChars(formattedValue: string): void {
        for (const [i, char] of formattedValue.entries()) {
            console.log(`Key: ${i} Value: ${char}`);
        }
    }

The problem is that entries is not a valid function on a string. TS2239


An interesting observation is, that this appears only when the type definition is given by the function parameter. The autofix works correctly if a const parameter is used. The autofix does not change this code.

Original Code

    function foo(): void {
        const formattedValue = 'bla bla';

        for (let i = 0; i < formattedValue.length; i++) {
            const char = formattedValue[i];

            console.log(`Key: ${i} Value: ${char}`);
        }
    }

andrmoel avatar Oct 23 '23 11:10 andrmoel