typescript-eslint: Bug: [@typescript-eslint/no-unnecessary-type-assertion] False positives for "as const" assertions

Before You File a Bug Report Please Confirm You Have Done The Following…

  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have searched for related issues and found none that matched my issue.
  • I have read the FAQ and my problem is not listed.

Playground Link

https://typescript-eslint.io/play/#ts=5.4.2&fileType=.tsx&code=KYDwDg9gTgLgBAYwgOwM7wLYEMoGthRwC8cARNngaXFqoiugNwCwAUKJLHAJbIwEAzLAmBwAIlhhY4AbzZw4FfFABccGAE8wwCAMU5lLVgoBuWADYBXYGvRReAcyMBfNgMvIEMbikRRgksASUgAUAJRqwdJyxvRo8ABGtKIkMvqUqunKcM5GCv4wllDIsnAAdBVJqMAANHBmVjZk1LlszkA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0ipWkOTJE0fJQ5N0UOdA7RI4MAF8QOoA&tsconfig=N4KAvkA&tokens=false

Repro Code

export const marker = "marker" as const;
export interface Data {
  marker: typeof marker;
  value: string;
}
function createData(): Data {
  const base = { marker: marker };
  return { ...base, value: "" };
}

ESLint Config

module.exports = {
  "rules": {
    "@typescript-eslint/no-unnecessary-type-assertion": "error"
  }
}

tsconfig

{
}

Expected Result

The first line of this code should not report an error for the as const assertion, since this assertion is necessary - removing it is a TypeScript compilation error (see TypeScript playground).

Actual Result

Starting in typescript-eslint@7.3 (presumably https://github.com/typescript-eslint/typescript-eslint/pull/8558), the first line of this code reports a @typescript-eslint/no-unnecessary-type-assertion error.

Additional Info

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 11
  • Comments: 33 (24 by maintainers)

Commits related to this issue

Most upvoted comments

Coming back to this, I’m still in the camp of making the rule lenient by default and adding an opt-in off-by-default option to be more strict. Two reasons why:

  • The fact that TypeScript’s behavior is so mysterious as to make us need to check in with the team hints to me that this will be a big confusing pain point if we enable it by default
  • The as const practice in question is a common use case that people need - especially as evidenced by the big pushback here.

We could always turn the option on in strictTypeChecked - though IMO that should be a separate followup issue, to not block this one.

Proposal: let’s add this option as off-by-default for our current major version (v8), and treat turning it on by default as a separate followup issue?

This behaviour is intended in Typescript, to allow constant values to initialise mutable ones:

const start = 1001;
const max = 100000;
// many (thousands?) of lines later ...
for (let i = start; i < max; i = i + 1) {
  // did I just write a for loop?
  // is this a C program?
}

(From https://github.com/microsoft/TypeScript/wiki/Reference-Checker-Widening-Narrowing#literal-widening)

The best way to write this, in my opinion, is @kirkwaiblinger’s second suggestion – although it would be even better if Typescript allowed as const on object properties.

Even better, if the program allows, is to use "marker" everywhere instead of extracting to a const variable. The compiler checks "marker" everywhere Data is used from here on out, so there shouldn’t be a problem with typos which I guess is one reason for extracting to a variable.

I don’t know the specifics of no-unnecessary-type-assertion, but I guess that preferring as const on mutable locations instead of immutable ones means that it’s currently correct and doesn’t need to change.

The fact that TS widens the object type to have marker: string unless the variable declaration is specifically marked with as const seems like counter-intuitive and incorrect behaviour.

It’s probably worth filing an issue upstream.

Maybe, but as it stands the rule is doing more harm than good by wrongly flagging such as const as safely removable.

This seems like a bug in TS. Without the as const the type of marker is "marker". With it the type is the same.

This is evidenced by the fact that TS types your interface as requiring the property marker: "marker", not marker: string.

The fact that TS widens the object type to have marker: string unless the variable declaration is specifically marked with as const seems like counter-intuitive and incorrect behaviour.

It’s probably worth filing an issue upstream.

the rule would report and be correct 92% of the time

is a terrible false positive rate.

I’d suggest simply allowing as const, if applied to a literal that can be widened.

I’d say option 1 is best too - we don’t want to skip reporting cos otherwise most of the rule’s reports would go away.

We should be able to auto detect this case using scope analysis.

Hey guys, would prefer option 3 - never report it; Since it does make a difference in TypeScript, and is a pretty popular feature of the language (even though more on the advanced side).

Here’s another example where it makes a difference:

With as const:

export const defaultLanguage = "en" as const;

const languages = [defaultLanguage];
type DefaultLanguage = (typeof languages)[number];

const lang: DefaultLanguage = "fr"; // Type '"fr"' is not assignable to type '"en"'.ts(2322)

Without as const:

export const defaultLanguage = "en";

const languages = [defaultLanguage];
type DefaultLanguage = (typeof languages)[number];

const lang: DefaultLanguage = "fr"; // const lang: string

Please at least provide an option for advanced TS users to allow as const case. Of course it would be awesome if we could auto-detect type widening possibilities, but probably isn’t worth the effort on linter side.

My perspective here: We have a codebase with ~300 scattered cases of export const FOO = 'foo' as const;, which all get flagged by this rule. The auto-fix removes as const and results in ~25 scattered TypeScript errors. We currently have the rule disabled because of this, with a comment linked to this issue. I’d love to enable it (it’s a useful rule!) without introducing ~300 eslint-disable directives. Remember, these are false positives, since removing as const risks breaking any importing code. In fact, even for true positives where const ... as const can be safely changed as the code stands, I don’t necessarily want to do so, since it isn’t the same and can matter later on.

I’d rather just disable this specific aspect of the rule (option 2) or at least have an option to do so (option 3), i.e., to always allow type assertions that affect freshness.

I’ve just learned that TS appears to have intentional behavior around the “freshness” of a const variable type (see https://github.com/microsoft/TypeScript/pull/52473#discussion_r1096104099), though it’s not clear that it’s a particularly external-facing concept. Would have to do some more research.

In any case, I think it explains what we’re seeing here, though I’m not sure that it is obvious what we should actually do about it.

@bradzacher, thoughts?

Would it be possible for typescript-eslint to detect whether or not a constant variable is later used as part of type inference for another variable (i.e. a let or an object declaration) in order to decide whether or not an as const assertion is unnecessary?

That is a really nifty idea. It would be nice to only add this exemption when it’s helpful… But also type inference is a really tricky algorithm to try to re-implement - even just this subset. This feels like a good followup issue & deeper investigation.

Would it be possible for typescript-eslint to detect whether or not a constant variable is later used as part of type inference for another variable (i.e. a let or an object declaration) in order to decide whether or not an as const assertion is unnecessary?

Uh oh! @Maxim-Mazurok, the image you shared is missing helpful alt text. Check https://github.com/typescript-eslint/typescript-eslint/issues/8721#issuecomment-2443230619.

Alt text is an invisible description that helps screen readers describe images to blind or low-vision users. If you are using markdown to display images, add your alt text inside the brackets of the markdown image.

Learn more about alt text at Basic writing and formatting syntax: images on GitHub Docs.

🤖 Beep boop! This comment was added automatically by github/accessibility-alt-text-bot.

Agreed. I don’t love potentially falsely erroring on a case users are likely to hit, but this is a somewhat niche edge case and pretty easy to work around. +1 to option 1.

@sandersn Many, many thanks for the excellent explanation and also the helpful reference to the typescript wiki! 🙏

This info also helps us simplify the repro considerably:

const freshMarker = 'marker';
let mutableMarker = freshMarker;
const notAssignableDueToWidening: 'marker' = mutableMarker; // TS ERROR - can't assign string to 'marker'

vs

const unfreshMarker = 'marker' as const; // TYPESCRIPT-ESLINT ERROR - no-unnecessary-type-assertion
let mutableMarker = unfreshMarker;
const assignable: 'marker' = mutableMarker; 

It’s not immediately obvious to me what the best behavior for the rule would be in light of this info.

In theory, it might make sense to update the check to be: if the type before and after the assertion are the same and it’s not in a context in which freshness could be impacted, consider it an unnecessary type assertion.

Seems there’s also a good argument that usually the freshness/unfreshness isn’t necessary or desired, so from a developer perspective this probably is an unnecessary type assertion in most cases, albeit not one that behaves identically after removing (and therefore which may need to be disabled when the unfresh behavior is genuinely desired).

@typescript-eslint/triage-team

Marking as blocked on someone filing an issue on TypeScript.

Posed a question in the TS discord to start 👍 (see https://discord.com/channels/508357248330760243/640177429775777792/1247058925401149482)

@kirkwaiblinger I agree with you that we should get clarity on whether this is a TypeScript bug. +1 that it seems odd how having the as const on line 1 doesn’t change the reported type of the const marker, but does change the type of the const base = { marker: marker }.

Marking as blocked on someone filing an issue on TypeScript.

I also note that putting const marker = 'marker' as 'marker' also has the same impact in these examples as const marker = 'marker' as const.

I guess it seems like we’re running into a case where a type assertion has broader effect than setting the type of the thing being asserted on.

Curious what other team members think

works… and makes a whole lot more sense anyway.

In this case, yes, but that will affect all other attributes of the object. For example, if base were of a type with an array attribute, applying as const to base would type that array as readonly. (see this playground)

@kgregory yeah, that’s a fair point. and that irked me too. See https://github.com/typescript-eslint/typescript-eslint/issues/8721#issuecomment-2104880497 for 3 more examples that don’t though 🤣

-export const marker = "marker" as const;
+export const marker = "marker";
export interface Data {
  marker: typeof marker;
  value: string;
}
function createData(): Data {
- const base = { marker: marker };
+ const base: { marker: typeof marker } = { marker: marker };
  return { ...base, value: "" };
}

works also.

As does

-export const marker = "marker" as const;
+export const marker = "marker";
export interface Data {
  marker: typeof marker;
  value: string;
}
function createData(): Data {
- const base = { marker: marker };
+ const base = { marker: marker as typeof marker };
  return { ...base, value: "" };
}

and, of course

-export const marker = "marker" as const;
+export const marker = "marker";
export interface Data {
  marker: typeof marker;
  value: string;
}
function createData(): Data {
 const base = { marker: marker };
- return { ...base, value: "" };
+ return { marker, value: "" };
}

So it has something to do specifically with the widening behavior when creating a mutable object whose type is inferred. More I think about it, it really just seems surprising to me personally that the example in the issue report works in the first place.

works… and makes a whole lot more sense anyway.

In this case, yes, but that will affect all other attributes of the object. For example, if base were of a type with an array attribute, applying as const to base would type that array as readonly. (see this playground)

Hmmmm, note also that

-export const marker = "marker" as const;
+export const marker = "marker";
export interface Data {
  marker: typeof marker;
  value: string;
}
function createData(): Data {
- const base = { marker: marker };
+ const base = { marker: marker } as const;
  return { ...base, value: "" };
}

works… and makes a whole lot more sense anyway. It seems really odd that using as const in the first line would have an effect on the type of base granted marker has the same type whether or not as const is explicitly used.