Skip to content

Rule proposal: no-unnecessary-coercion #8515

Closed
@skondrashov

Description

@skondrashov

Before You File a Proposal Please Confirm You Have Done The Following...

My proposal is suitable for this project

  • My proposal specifically checks TypeScript syntax, or it proposes a check that requires type information to be accurate.
  • My proposal is not a "formatting rule"; meaning it does not just enforce how code is formatted (whitespace, brace placement, etc).
  • I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).

Description

I'd like String(something), something.toString(), and perhaps something as string to show an error if something is a string already, but to be allowed if it's a string | number or even a string | number | undefined. This is similar to the proposal at #6385 but it appears there're some issues with doing this with numbers that I don't think applies to strings.

In my case, I would like to do this because I am working with a library that exports a string | number | undefined, but I believe their type is incorrect, and I would like to essentially be notified that I can remove my casts if the type changes and becomes a string instead, and I believe similar use cases would not be exceeding rare, where one might be able to catch useless casts after updating one type somewhere, whether in a library or in their own type definitions. My feeling is that if this were turned on it would trigger errors in more than a couple of codebases. In reference to the similar issue for numbers, I do support the implementation of that as well for similar reasons.

Fail Cases

let replace = 'me';
replace = String(replace)

Pass Cases

let replace: string | number = 'me';
replace = String(replace)

Additional Info

This is also similar to eslint's https://eslint.org/docs/latest/rules/no-extra-boolean-cast, which I'm actually not sure how they achieve without typescript, but that rule makes a lot of sense to me as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issueenhancement: new plugin ruleNew rule request for eslint-pluginlocked 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