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
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
- feat(eslint-plugin): add option to ignore string const assertiions in no-unnecessary-type-assertion rule Fixes #8721 — committed to KuSh/typescript-eslint by KuSh 2 years ago
- feat(eslint-plugin): add option to ignore string const assertiions in no-unnecessary-type-assertion rule Fixes #8721 — committed to KuSh/typescript-eslint by KuSh 2 years ago
- feat(eslint-plugin): add option to ignore string const assertiions in no-unnecessary-type-assertion rule Fixes #8721 — committed to KuSh/typescript-eslint by KuSh 2 years ago
- feat(eslint-plugin): add option to ignore string const assertiions in no-unnecessary-type-assertion rule Fixes #8721 — committed to KuSh/typescript-eslint by KuSh 2 years ago
- feat(eslint-plugin): add option to ignore string const assertiions in no-unnecessary-type-assertion rule Fixes #8721 — committed to KuSh/typescript-eslint by KuSh 2 years ago
- feat(eslint-plugin): [no-unnecessary-type-assertion] add option to ignore string const assertions (#10979) * feat(eslint-plugin): add option to ignore string const assertiions in no-unnecessary-type-... — committed to JoshuaKGoldberg/typescript-eslint by KuSh 2 years ago
- feat(eslint-plugin): [no-unnecessary-type-assertion] add option to ignore string const assertions (#10979) * feat(eslint-plugin): add option to ignore string const assertiions in no-unnecessary-type-... — committed to phaux/typescript-eslint by KuSh 2 years ago
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:
as constpractice 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:
(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 conston object properties.Even better, if the program allows, is to use
"marker"everywhere instead of extracting to aconstvariable. The compiler checks"marker"everywhereDatais 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 conston mutable locations instead of immutable ones means that it’s currently correct and doesn’t need to change.Maybe, but as it stands the rule is doing more harm than good by wrongly flagging such
as constas safely removable.This seems like a bug in TS. Without the
as constthe type ofmarkeris"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", notmarker: string.The fact that TS widens the object type to have
marker: stringunless the variable declaration is specifically marked withas constseems like counter-intuitive and incorrect behaviour.It’s probably worth filing an issue upstream.
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:Without
as const:Please at least provide an option for advanced TS users to allow
as constcase. 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 removesas constand 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 ~300eslint-disabledirectives. Remember, these are false positives, since removingas constrisks breaking any importing code. In fact, even for true positives whereconst ... as constcan 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
constvariable 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?
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-eslintto detect whether or not a constant variable is later used as part of type inference for another variable (i.e. aletor an object declaration) in order to decide whether or not anas constassertion 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.
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:
vs
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
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 conston line 1 doesn’t change the reported type of theconst marker, but does change the type of theconst 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 asconst 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.
as constassertions or having this sort of false positive edge case (wouldn’t be the only one either, see https://github.com/typescript-eslint/typescript-eslint/issues/9007).Curious what other team members think
@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 🤣
works also.
As does
and, of course
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.
In this case, yes, but that will affect all other attributes of the object. For example, if
basewere of a type with an array attribute, applyingas consttobasewould type that array asreadonly. (see this playground)Hmmmm, note also that
works… and makes a whole lot more sense anyway. It seems really odd that using
as constin the first line would have an effect on the type ofbasegrantedmarkerhas the same type whether or notas constis explicitly used.