Skip to content

Enhancement: [consistent-type-assertions] Prefer type annotation over assertion for arrays #6374

@JoshuaKGoldberg

Description

@JoshuaKGoldberg

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

Code should not use an as type assertion when a : type annotation would do. In some cases (see examples later) they act the same, but as assertions are generally something that should be avoided whenever possible. as removes some type safety from TypeScript. Not ideal.

Fail Cases

const errorMessages = [] as string[];

Pass Cases

const errorMessages: string[] = [];

Additional Info

This should also trigger for arrays that have contents in them.

- const errorMessages = ['a'] as string[];
+ const errorMessages: string[] = ['a'];

Alas, knowing whether the assertion actually was doing anything important is blocked on my favorite TypeScript issue microsoft/TypeScript#9879. But since folks really shouldn't be using an assertion for a variable with an initial value, I'm ok with this edge case bug being in the rule:

// The + is now an error... 😈 deal with it!
- const errorMessages2 = [Math.random() ? 'a' : 'b'] as 'a'[];
+ const errorMessages3: 'a'[] = [Math.random() ? 'a' : 'b'];

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