microsoft/rushstack

[eslint-config] Proposal: Allow inferred types for `const`s written `as const`

alber70g opened this issue · 1 comments

Summary

Allow as const to be without type, as type inference will be more correct as falling back to Record<string, string> or even string is undesirable.

Repro steps

Details

The current implementation of the typedef-var rule requires developers to explicitly specify types for variables, even when utilizing the as const assertion. This approach can lead to less accurate type annotations, especially when dealing with large objects, as developers may resort to generic types such as Record<string, string>.

Consider the following examples:

  1. Single Value:

    const myConstant = "the constant";
    // Typed as string vvvvv, losing the real value
    const myConstant: string = "the constant";
    

    Instead of the more accurate:

    const myConstant: "the constant" = "the constant";
    
  2. Object:

    const CONSTANTS = {
      a: "first",
      b: "another"
    };
    // With larger objects likely typed as Record<string, string>
    

    Instead of the more accurate:

    const CONSTANTS: { a: "first"; b: "another" } = {
      a: "first",
      b: "another"
    };
    

Proposed Solution:

I propose allowing the omission of explicit types when using the as const assertion. This would enable developers to leverage TypeScript's type inference capabilities and still ensure accurate type representation.

Example of valid ✅ code:

const CONSTANTS = {
  a: "first",
  b: "another"
} as const;

Example of invalid ❌ code:

const CONSTANTS = {
  a: "first",
  b: "another"
};

Benefits

  1. Accurate Type Inference: Developers can rely on TypeScript's type inference to deduce precise types, reducing the likelihood of inaccuracies in type annotations.

  2. Improved Readability: The code becomes more concise and readable, especially for larger objects, without sacrificing type accuracy.

  3. Consistency with Best Practices: Aligns with best practices of leveraging TypeScript's type inference whenever possible to reduce redundancy and enhance code maintainability.

Standard questions

Please answer these questions to help us investigate your issue more quickly:

Question Answer
@rushstack/eslint-config version?
Operating system?
Would you consider contributing a PR?
TypeScript compiler version?
Node.js version (node -v)?

This seems very useful. @alber70g - Would you be interested in implementing this?