Skip to content

[no-base-to-string] add option to prevent usage of Array .join on non-toString things #3388

Closed
@lydell

Description

@lydell

(Note: I couldn’t find any issue template/info about feature requests, I hope this is ok! 🙏 )

Summary: Disallow .join() calls on Arrays that aren’t Array<string>.

Motivation:

I had a function like this:

function noCommonRoot(paths: Array<string>): string {
  return `
I could not find a common ancestor for these paths:

${paths.join("\n")}

Files on different drives is not supported.
  `.trim();
}

I had trouble with using too much string types an mixing stuff up, so I introduced an AbsolutePath type to help me, and replaced string with AbsolutePath in many places.

type AbsolutePath = { tag: "AbsolutePath"; absolutePath: string };

function noCommonRoot(paths: Array<AbsolutePath>): string {
  return `
I could not find a common ancestor for these paths:

${paths.join("\n")}

Files on different drives is not supported.
  `.trim();
}

When I had fixed all compile errors, I had accidentally introduced a bug! noCommonRoot now outputs:

I could not find a common ancestor for these paths:

[object Object]
[object Object]
[object Object]

Files on different drives is not supported.

Oops!

I searched for .join in the entire project and switched to using this function instead, to avoid this problem in the future:

function join(array: Array<string>, separator: string): string {
  return array.join(separator);
}

That way I could fix the noCommonRoot function:

function noCommonRoot(paths: Array<AbsolutePath>): string {
  return `
I could not find a common ancestor for these paths:

${join(
  paths.map((path) => path.absolutePath),
  "\n"
)}

Files on different drives is not supported.
  `.trim();
}

Bonus: my join function requires the separator argument. That would be nice to lint too. The default "," is never what I want.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issueenhancement: plugin rule optionNew rule option for an existing eslint-plugin rulelocked due to agePlease open a new issue if you'd like to say more. See https://typescript-eslint.io/contributing.package: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions