Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat(eslint-plugin): add rule [strict-void-return]#9707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
phaux wants to merge60 commits intotypescript-eslint:main
base:main
Choose a base branch
Loading
fromphaux:strict-void-return

Conversation

phaux
Copy link
Contributor

@phauxphaux commentedAug 2, 2024
edited
Loading

PR Checklist

Overview

So basically I implemented the void checking as requested by#2988. For every checked node (arguments, assignments, returns, etc) I take the actual function type and the contextual function type and compare return types. Only object method shorthand required slightly different logic.

That already worked pretty well, but I also found#1744 and decided to include it in this rule as well, since I already had a similar thing implemented for object shorthand methods.I added this as an optionconsiderBaseClass andconsiderImplementedInterfaces, enabled by default.

Then I noticed that callback foraddEventListener is not detected as void context. That's because it has another signature where the callback can returnany. I was stuck on this for a long time. Ultimately I looked at howno-misused-promises does this and implemented something similarasconsiderOtherSignatures option, enabled by default.

At this point this rule already did everythingno-misused-promises'scheckVoidReturn did, but better. It doesn't have problems like#8054 or#8739. Maybe it's worth splittingno-misused-promises into 3 separate rules in the future? (this one being one of them)

EDIT: autofixes removed for now

I also added many autofixes and suggestions. They are possible when the provided function is a function literal and we can inspect its body. Some of them are the same as inno-confusing-void-expression so I moved them into utils. It might make sense to change some autofixes into suggestions instead so they don't accidentally remove a big chunk of code. Let me know if that's a good idea.

The biggest feature is automatic suggestions which I and probably others had to type manually a thousand of times:

takesCallback(async()=>{block;});

into

takesCallback(()=>{(async()=>{block;})().catch(err=>{});});

or

// eslint-disable-next-line @typescript-eslint/no-misused-promisestakesCallback(async()=>{try{block;}catch{}});

To allow the second suggestion without the need of ignoring the line I added the optionallowReturnPromiseIfTryCatch. It's just a simple extraif near the end of the long routine that checks everything that could be wrong in the function body. I hope it can stay.

kirkwaiblinger, JoshuaKGoldberg, and alythobani reacted with heart emoji
@typescript-eslint
Copy link
Contributor

Thanks for the PR,@phaux!

typescript-eslint is a 100% community driven project, and we are incredibly grateful that you are contributing to that community.

The core maintainers work on this in their personal time, so please understand that it may not be possible for them to review your work immediately.

Thanks again!


🙏Please, if you or your company is finding typescript-eslint valuable, help us sustain the project by sponsoring it transparently onhttps://opencollective.com/typescript-eslint.

@netlifyNetlify
Copy link

netlifybot commentedAug 2, 2024
edited
Loading

Deploy Preview fortypescript-eslint failed.

NameLink
🔨 Latest commitaad8977
🔍 Latest deploy loghttps://app.netlify.com/projects/typescript-eslint/deploys/687ac8f36f75d50008e5338e

@nx-cloudNx Cloud
Copy link

nx-cloudbot commentedAug 2, 2024
edited
Loading

View yourCI Pipeline Execution ↗ for commitaad8977

CommandStatusDurationResult
nx test eslint-plugin --coverage=false❌ Failed5m 21sView ↗
nx test eslint-plugin❌ Failed5m 13sView ↗
nx run-many -t lint✅ Succeeded3m 22sView ↗
nx run-many -t typecheck✅ Succeeded2m 20sView ↗
nx test eslint-plugin-internal --coverage=false✅ Succeeded4sView ↗
nx test typescript-estree --coverage=false✅ Succeeded2sView ↗
nx run types:build✅ Succeeded5sView ↗
nx run integration-tests:test✅ Succeeded4sView ↗
Additional runs (26)✅ Succeeded...View ↗

☁️Nx Cloud last updated this comment at2025-07-18 22:30:33 UTC

@kirkwaiblingerkirkwaiblinger added the enhancement: new plugin ruleNew rule request for eslint-plugin labelAug 5, 2024
@codecovCodecov
Copy link

codecovbot commentedAug 5, 2024
edited
Loading

Codecov Report

Attention: Patch coverage is98.22335% with7 lines in your changes missing coverage. Please review.

Project coverage is 90.91%. Comparing base(f9bd7d8) to head(3cad6b9).
Report is 32 commits behind head on main.

Current head3cad6b9 differs from pull request most recent headaad8977

Pleaseupload reports for the commitaad8977 to get more accurate results.

Files with missing linesPatch %Lines
...slint-plugin/src/util/getBaseTypesOfClassMember.ts78.78%7 Missing⚠️
Additional details and impacted files
@@            Coverage Diff             @@##             main    #9707      +/-   ##==========================================+ Coverage   90.84%   90.91%   +0.06%==========================================  Files         501      504       +3       Lines       50919    51381     +462       Branches     8387     8506     +119     ==========================================+ Hits        46256    46711     +455- Misses       4648     4655       +7  Partials       15       15
FlagCoverage Δ
unittest90.91% <98.22%> (+0.06%)⬆️

Flags with carried forward coverage won't be shown.Click here to find out more.

Files with missing linesCoverage Δ
packages/eslint-plugin/src/configs/eslintrc/all.ts100.00% <100.00%> (ø)
...lugin/src/configs/eslintrc/disable-type-checked.ts100.00% <100.00%> (ø)
packages/eslint-plugin/src/configs/flat/all.ts100.00% <100.00%> (ø)
...nt-plugin/src/configs/flat/disable-type-checked.ts100.00% <100.00%> (ø)
...ages/eslint-plugin/src/rules/strict-void-return.ts100.00% <100.00%> (ø)
packages/eslint-plugin/src/util/walkStatements.ts100.00% <100.00%> (ø)
...slint-plugin/src/util/getBaseTypesOfClassMember.ts78.78% <78.78%> (ø)

... and3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JoshuaKGoldberg
Copy link
Member

JoshuaKGoldberg commentedAug 10, 2024
edited
Loading

👋 Exciting PR, really looking forward to the rule! Just marking as a draft because there are unit test failures. This keeps getting me excited when it pops up in my notifications 😄. Let us know if you want to talk or ask questions about any of them.

Edit: ACK on the questions in the OP, I don't have the bandwidth to answer just now, but hopefully someone else does. Please ping us if those are blocking progress!

@JoshuaKGoldbergJoshuaKGoldberg marked this pull request as draftAugust 10, 2024 02:49
@phaux
Copy link
ContributorAuthor

Fixed and I'm not planning any more changes so I'm undrafting it I guess.

JoshuaKGoldberg reacted with thumbs up emojiJoshuaKGoldberg reacted with rocket emoji

@phauxphaux marked this pull request as ready for reviewAugust 10, 2024 15:48
Copy link
Member

@JoshuaKGoldbergJoshuaKGoldberg left a comment
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

OK! Very happy to have finally made it to this PR: it's a great piece of work. As you said, it covers a heck of a lot of functionality, and does so in ways that are really solid compared to previous approaches. Fantastic! 👏

It's also alot of code that was hard to read through. For an initial version of the rule, I think nuance around suggestions aren't necessary. And the fixers would need to be suggestions given they change code behavior.

I left requests for simplification through the code: for messages, options, and the suggestions.

But, my advice would be to hold off applying that large set of removals until the conversation inhttps://github.com/typescript-eslint/typescript-eslint/pull/9707/files#r1741336663 is resolved. The consensus might end up being that the options are good and useful after all.

Keanu Reaves as Neo in The Matrix saying 'whoa'

}
},
AssignmentExpression:(node):void=>{
if(['=','||=','&&=','??='].includes(node.operator)){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

[Testing] If I remove thisif and just leave its body, all unit tests still pass. That means there's at least a missing test case.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

This is still the case.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Added a test but it doesn't matter:

declareletfoo:()=>void;foo+=()=>1;

still doesn't fail with condition removed.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Sounds to me like theif can be removed, then! 🔪

Change request: remove theif?

Just noting for posterity,node.operator in anAssignmentExpression can be any of:

"="|"+="|"-="|"*="|"**="|"/="|"%="|"<<="|">>="|">>>="|"&="|"|="|"||="|"&&="|"??="|"^="

The operators not mentioned in theif all produce TypeScript errors when given functions. So I agree with adding thevalid test case containingfoo += () => 1. That makes sure the removal of theif doesn't break those cases.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

At this point this rule already did everythingno-misused-promises'scheckVoidReturn did, but better. It doesn't have problems#8054 or#8739. Maybe it's worth splittingno-misused-promises into 3 separate rules in the future? (this one being one of them)

This is a great question.no-misused-promises was already largely overlapped byno-unnecessary-condition. This newstrict-void-return pretty much takes on the rest ofno-misused-promises, makingno-misused-promises redundant if you have bothno-unnecessary-condition andstrict-void-return...

I'd be in favor of deprecatedno-misused-promises in favor of usingno-unnecessary-condition +strict-void-return. The only benefit I can think of forno-misused-promises would be projects that want toonly apply the checks for Promises... Maybe these two rules could each be given some kind of"only check Promises" option?

Also of note is thatno-misused-promises'scheckVoidReturns is pretty configurable. Maybe, if this rule is to replaceno-misused-promises, it'd be useful to have each of those configurable options? Or, on the other hand, maybe those options are holdovers that real-world don't generally use? Investigation needed. I think those options can be a followup & shouldn't block this PR.

What do you think?

Also cc: @typescript-eslint/triage-team in general, and@kirkwaiblinger +@alythobani from#8765.

alythobani reacted with thumbs up emoji
Copy link
Contributor

@alythobanialythobaniSep 6, 2024
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

no-misused-promises was already largely overlapped by no-unnecessary-condition. This new strict-void-return pretty much takes on the rest of no-misused-promises, making no-misused-promises redundant if you have both no-unnecessary-condition and strict-void-return...

Yeah the only thing left I think would be thechecksSpreads option:

constmyPromise=Promise.resolve({num:2,str:"2"});constmyObject={...myPromise};// Expected a non-Promise value to be spreaded in an object. eslint(@typescript-eslint/no-misused-promises)

I do agree it could make sense to replacechecksVoidReturn withstrict-void-return. Although there may be tradeoffs in terms of eng effort and/or UX complexity if we wanted to retain all the configurability on top of having anonlyChecksPromises option.

As forchecksConditionals, I actually just foundmicrosoft/TypeScript#34717 andmicrosoft/TypeScript#39175—looks likecheckConditionals has been covered by TypeScript for a couple years now :)

The only benefit I can think of for no-misused-promises would be projects that want to only apply the checks for Promises

Yeah e.g. one example I've seen when looking into this topic (void function assignability), isusingpush withforEach:

declarefunctionforEach<T>(arr:T[],callback:(el:T)=>void):void;lettarget:number[]=[];forEach([1,2,3],el=>target.push(el));// OK

It's possible some users would prefer to only check Promises so they can still use shorthands like the above without linter errors (and/or just mainly care about forgetting toawait Promises), in which case anonlyChecksPromises option would be useful if we did replacechecksVoidReturn withstrict-void-return.

Maybe, if this rule is to replace no-misused-promises, it'd be useful to have each of those configurable options? Or, on the other hand, maybe those options are holdovers that real-world don't generally use?

It looks like#4619 was originally the impetus for adding the options (#4623); and based on the thread it looks like there are at least a few people who find the configurability you added very helpful!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Maybe a lame response, but is there a compelling reason not to land this first, then consider the no-misused-promises deprecation, and which options we might need to port or create in order to do so, afterwards?

Just thinking, deprecating no-misused-promises might have some strings attached, such as some nontrivial updating of the docs in no-floating-promises that explain how to lint against promise antipatterns outside of ExpressionStatements.

JoshuaKGoldberg and alythobani reacted with thumbs up emoji

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Agreed with landing this first, then considering a deprecation as a followup.

In fact, this rule is pretty big and scary. We don't really have a process for declaring rules as "canary" or "experimental".#8676 is the closest we have to a feature request. Maybe we should set a precedent?

(I don't think this PR should be blocked on that)

@JoshuaKGoldbergJoshuaKGoldberg added the awaiting responseIssues waiting for a reply from the OP or another party labelSep 3, 2024
Copy link
Contributor

@alythobanialythobani left a comment
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Very cool PR, great job sticking it out and a lot of thought put into things!

Left some thoughts/questions, hope they're helpful 🌅

Copy link
Contributor

@alythobanialythobaniSep 6, 2024
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

no-misused-promises was already largely overlapped by no-unnecessary-condition. This new strict-void-return pretty much takes on the rest of no-misused-promises, making no-misused-promises redundant if you have both no-unnecessary-condition and strict-void-return...

Yeah the only thing left I think would be thechecksSpreads option:

constmyPromise=Promise.resolve({num:2,str:"2"});constmyObject={...myPromise};// Expected a non-Promise value to be spreaded in an object. eslint(@typescript-eslint/no-misused-promises)

I do agree it could make sense to replacechecksVoidReturn withstrict-void-return. Although there may be tradeoffs in terms of eng effort and/or UX complexity if we wanted to retain all the configurability on top of having anonlyChecksPromises option.

As forchecksConditionals, I actually just foundmicrosoft/TypeScript#34717 andmicrosoft/TypeScript#39175—looks likecheckConditionals has been covered by TypeScript for a couple years now :)

The only benefit I can think of for no-misused-promises would be projects that want to only apply the checks for Promises

Yeah e.g. one example I've seen when looking into this topic (void function assignability), isusingpush withforEach:

declarefunctionforEach<T>(arr:T[],callback:(el:T)=>void):void;lettarget:number[]=[];forEach([1,2,3],el=>target.push(el));// OK

It's possible some users would prefer to only check Promises so they can still use shorthands like the above without linter errors (and/or just mainly care about forgetting toawait Promises), in which case anonlyChecksPromises option would be useful if we did replacechecksVoidReturn withstrict-void-return.

Maybe, if this rule is to replace no-misused-promises, it'd be useful to have each of those configurable options? Or, on the other hand, maybe those options are holdovers that real-world don't generally use?

It looks like#4619 was originally the impetus for adding the options (#4623); and based on the thread it looks like there are at least a few people who find the configurability you added very helpful!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Maybe a lame response, but is there a compelling reason not to land this first, then consider the no-misused-promises deprecation, and which options we might need to port or create in order to do so, afterwards?

Just thinking, deprecating no-misused-promises might have some strings attached, such as some nontrivial updating of the docs in no-floating-promises that explain how to lint against promise antipatterns outside of ExpressionStatements.

JoshuaKGoldberg and alythobani reacted with thumbs up emoji
@github-actionsgithub-actionsbot removed the awaiting responseIssues waiting for a reply from the OP or another party labelApr 25, 2025
@phaux
Copy link
ContributorAuthor

Ready

skondrashov reacted with eyes emoji

@JoshuaKGoldbergJoshuaKGoldberg removed the stalePRs or Issues that are at risk of being or have been closed due to inactivity for a prolonged period labelJun 18, 2025
Copy link
Member

@JoshuaKGoldbergJoshuaKGoldberg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

OK! Sorry this took so long to get a review - it's a really wonderful new rule and has a lot of nuance that I wanted to give the attention it deserves. The functionality generally looks great to me, I think you nailed a lot of the hard-to-get-right cases. Awesome! 👏

I'm mostly requesting changes to address the logical branches that don't seem to impact unit tests when removed. For each, some code change should be done: either adding tests for a necessary runtime check or removing code (possibly also fiddling with types) for an unnecessary-at-runtime check.

I also took a pass at docs. They don't have to be perfect for merge, we can always touch them up as we go.

Thanks for bringing this back into review, it's a really exciting rule!

}
},
AssignmentExpression:(node):void=>{
if(['=','||=','&&=','??='].includes(node.operator)){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Sounds to me like theif can be removed, then! 🔪

Change request: remove theif?

Just noting for posterity,node.operator in anAssignmentExpression can be any of:

"="|"+="|"-="|"*="|"**="|"/="|"%="|"<<="|">>="|">>>="|"&="|"|="|"||="|"&&="|"??="|"^="

The operators not mentioned in theif all produce TypeScript errors when given functions. So I agree with adding thevalid test case containingfoo += () => 1. That makes sure the removal of theif doesn't break those cases.

return(
// At least one return type is void
returnTypes.some(type=>
tsutils.isTypeFlagSet(type,ts.TypeFlags.Void),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

[Question] This usesVoid but the next check usesVoidLike. Swapping to any other combination of the type flags doesn't produce any test failures. Was there a reason to choose one vs. the other?

I'm genuinely asking, I don't know 😄

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

dunno

Comment on lines 237 to 242
if(
propNode.value.type===AST_NODE_TYPES.AssignmentPattern||
propNode.value.type===AST_NODE_TYPES.TSEmptyBodyFunctionExpression
){
return;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

[Testing] Removing thisif check doesn't fail any unit tests. Either this check should exist and tests are missing, or this is dead code that can be removed.

Similar note to earlier on the type narrowing.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I think in this case the types are wrong.

AFAIK it's not possible to have TSEmptyBodyFunctionExpression as an object's property value.{ f() } is an syntax error. This is only valid in an abstract class body.

AssignmentPattern is also not valid as value of Property of ObjectLiteral, but it is valid for Property of ObjectPattern. Types could be improved by splitting Property into 2 types.

I will add type assertions for now.

Comment on lines +290 to +292
if(propNode.value==null){
return;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

[Testing] Removing thisif check doesn't fail any unit tests. Either this check should exist and tests are missing, or this is dead code that can be removed.

Copy link
ContributorAuthor

@phauxphauxJul 11, 2025
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

There is already a test for this and if I remove this check then the types are wrong. TS functions say they don't accept null but if you pass null they just do nothing and return more null so nothing crashes.

Comment on lines 316 to 323
if(
methodNode.value.type===AST_NODE_TYPES.TSEmptyBodyFunctionExpression
){
return;
}
if(methodNode.kind!=='method'){
return;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

[Testing] Removing thisif checks doesn't fail any unit tests. Either they should exist and tests are missing, or this is dead code that can be removed.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Added test for empty body func.

Removingkind == 'method' actually makes the rule catch more cases.

JoshuaKGoldberg reacted with rocket emoji
JSXAttribute:(node):void=>{
if(
node.value?.type===AST_NODE_TYPES.JSXExpressionContainer&&
node.value.expression.type!==AST_NODE_TYPES.JSXEmptyExpression

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

[Testing] Removing the&& node.value... !== JSXEmptyExpression doesn't fail any unit tests. Either this check should exist and tests are missing, or this is dead code that can be removed.

If the reason it's here is to narrownode.value.expression's type down toTSESTree.Expression then maybe either the types are suggesting a legit case to handle, or are wrong?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Added valid tests for JSXEmptyExpression (prop={}) and JSXElement (prop=<elem/>) but I dunno how to get JSXSpreadChild.
I triedprop={...value} but it doesn't work.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Oh if that's just not doable in the AST then we can just ignore it. A good followup issue would be to tighten up the AST types to not include it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Agreed with landing this first, then considering a deprecation as a followup.

In fact, this rule is pretty big and scary. We don't really have a process for declaring rules as "canary" or "experimental".#8676 is the closest we have to a feature request. Maybe we should set a precedent?

(I don't think this PR should be blocked on that)

@JoshuaKGoldbergJoshuaKGoldberg added the awaiting responseIssues waiting for a reply from the OP or another party labelJun 30, 2025
phauxand others added14 commitsJuly 9, 2025 21:35
Co-authored-by: Josh Goldberg ✨ <git@joshuakgoldberg.com>
Co-authored-by: Josh Goldberg ✨ <git@joshuakgoldberg.com>
Co-authored-by: Josh Goldberg ✨ <git@joshuakgoldberg.com>
Co-authored-by: Josh Goldberg ✨ <git@joshuakgoldberg.com>
Co-authored-by: Josh Goldberg ✨ <git@joshuakgoldberg.com>
Co-authored-by: Josh Goldberg ✨ <git@joshuakgoldberg.com>
Co-authored-by: Josh Goldberg ✨ <git@joshuakgoldberg.com>
@phaux
Copy link
ContributorAuthor

I need help with some of the review comments

@github-actionsgithub-actionsbot removed the awaiting responseIssues waiting for a reply from the OP or another party labelJul 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@alythobanialythobanialythobani left review comments

@kirkwaiblingerkirkwaiblingerkirkwaiblinger left review comments

@JoshuaKGoldbergJoshuaKGoldbergAwaiting requested review from JoshuaKGoldberg

Requested changes must be addressed to merge this pull request.

Assignees
No one assigned
Labels
enhancement: new plugin ruleNew rule request for eslint-plugin
Projects
None yet
Milestone
No milestone
4 participants
@phaux@JoshuaKGoldberg@alythobani@kirkwaiblinger

[8]ページ先頭

©2009-2025 Movatter.jp