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): [no-redundant-type-constituents] use assignability checking for redundancy checks#10744

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
mdm317 wants to merge41 commits intotypescript-eslint:main
base:main
Choose a base branch
Loading
frommdm317:7742-no-redundant-type-constituents

Conversation

mdm317
Copy link
Contributor

@mdm317mdm317 commentedJan 29, 2025
edited
Loading

PR Checklist

Overview

even cases where they're deeply equal, but declared as different object types.

This feature seems to overlap with this ruleno-duplicate-type-constituents so I'm not sure whether to include it.
For now, I'll remove it and proceed.

deeply equal

type ShallowEqual = number | number;type DeepEqual = { a: string } | { a: string };

Union
If x is assignable to y, then in the union x∣y, x is redundant and can be removed.
However, due to TypeScript'sExcess Property Checks feature, this logic did not work as expected.

For example, consider the union type{ a: 1 } | { a: 1, b: 1 }. Since{ a: 1, b: 1 } is assignable to{ a: 1 }
So{ a: 1, b: 1 } becomes redundant and can be removed.

However, if{ a: 1, b: 1 } is removed, the remaining type{ a: 1 } exhibits different behavior when declaring values.
For example,{ a: 1 } alone can only be assigned to variables of type{ a: 1 }, whereas{ a: 1 } | { a: 1, b: 1 } allows the declaration of both{ a: 1 } and{ a: 1, b: 1 }

Example code

type Foo = { a: 1 } | { a: 1, b: 1 }const foo: Foo = { a: 1 }const bar: Foo = { a: 1, b: 1 }type Foo2 = { a: 1 } const foo2: Foo2 = { a: 1 }const bar2: Foo2 = { a: 1, b: 1 } //error

So, before checking whether one type is assignable to another, I first verified that both objects have the same set of keys. Only then did I proceed with the assignability check.
ForA | B, i checks ifA andB have the same keys. If they do, it then checks assignability.

Union Types with Intersection Types

  • Union with a Single Intersection:
    • If a union type contains an intersection, like A | (B & C & D), the intersection (B & C & D) is treated as a single object type.
  • Union within an Intersection:
    • If an intersection includes a union, like A | (B & (C | D)), TypeScript simplifies the intersection into a union of intersections. B & (C | D) is equivalent to B & C | B & D,
    • This means the assignability check becomes: Is A assignable to (B & C) | (B & D)

Intersection
Unlike union types, intersection types did not need excess property checks.
A & B in this case ifA is assignable toB B is rebundant.

  • If there is no union type within the intersection, I proceed the assignability check.A & B
  • If there is union type, I check if every type in the union is compatible with the intersection and follows the same rules.
  • A & ( B | C)
A >= B, A >= C  Then  A >= (B | C)B >= A, C >= A  Then   (B | C) >= A

@typescript-eslint
Copy link
Contributor

Thanks for the PR,@mdm317!

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 commentedJan 29, 2025
edited
Loading

Deploy Preview fortypescript-eslint ready!

NameLink
🔨 Latest commite240759
🔍 Latest deploy loghttps://app.netlify.com/sites/typescript-eslint/deploys/67fe8a91cd0d740008558ccf
😎 Deploy Previewhttps://deploy-preview-10744--typescript-eslint.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 99 (🟢 up 3 from production)
Accessibility: 100 (no change from production)
Best Practices: 100 (no change from production)
SEO: 98 (no change from production)
PWA: 80 (no change from production)
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to yourNetlify site configuration.

@nx-cloudNx Cloud
Copy link

nx-cloudbot commentedJan 29, 2025
edited
Loading

View yourCI Pipeline Execution ↗ for commite240759.

CommandStatusDurationResult
nx typecheck ast-spec✅ Succeeded<1sView ↗
nx run-many --target=build --exclude website --...✅ Succeeded3sView ↗
nx run-many --target=clean✅ Succeeded11sView ↗

☁️Nx Cloud last updated this comment at2025-04-15 16:54:10 UTC

@codecovCodecov
Copy link

codecovbot commentedJan 29, 2025
edited
Loading

Codecov Report

Attention: Patch coverage is97.05215% with13 lines in your changes missing coverage. Please review.

Project coverage is 90.81%. Comparing base(be558e5) to head(e240759).
Report is 138 commits behind head on main.

Files with missing linesPatch %Lines
...plugin/src/rules/no-redundant-type-constituents.ts97.48%10 Missing and 1 partial⚠️
...escript-estree/src/semantic-or-syntactic-errors.ts0.00%2 Missing⚠️
Additional details and impacted files
@@            Coverage Diff             @@##             main   #10744      +/-   ##==========================================- Coverage   90.82%   90.81%   -0.01%==========================================  Files         497      497                Lines       50204    50368     +164       Branches     8274     8306      +32     ==========================================+ Hits        45600    45744     +144- Misses       4589     4608      +19- Partials       15       16       +1
FlagCoverage Δ
unittest90.81% <97.05%> (-0.01%)⬇️

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

Files with missing linesCoverage Δ
...t-plugin/src/rules/adjacent-overload-signatures.ts100.00% <ø> (ø)
...ages/eslint-plugin/src/rules/no-unsafe-argument.ts93.24% <100.00%> (ø)
...nt-plugin/src/rules/related-getter-setter-pairs.ts100.00% <ø> (ø)
...escript-estree/src/semantic-or-syntactic-errors.ts2.32% <0.00%> (ø)
...plugin/src/rules/no-redundant-type-constituents.ts97.45% <97.48%> (-0.20%)⬇️

... and1 file 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

👋 Ping@mdm317, are you planning on un-draft ing this soon? We'd prefer not to keep drafts around for too long in case someone else would want to send one too.

@mdm317
Copy link
ContributorAuthor

Sorry for the delay. This issue was more challenging than I expected.
I'll try to finish it within two days. If it takes longer, I'll close the PR and reopen it once it's resolved.
Moving forward, if I anticipate a delay, I'll close it first and reopen it when it's ready.

JoshuaKGoldberg reacted with heart emoji

@mdm317mdm317 marked this pull request as ready for reviewMarch 5, 2025 19:03
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 for the delay in reviewing. This is a really tricky one 😅.

I think the feature request is a lot trickier than the test cases here currently capture. It'll have to handle a lot of cases, including optional properties, interfaces extending each other, and so on. I suspect the core implementation will have to adjust a bunch - so left a few suggestions on how to reduce the amount of work done. Hope it's helpful, and let me know if you have questions! 🙌

mdm317 reacted with heart emoji

Choose a reason for hiding this comment

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

[Testing] There are going to be quite a few variants of types that could break the rule:

  • Conditional types
  • Generic types & their type parameters
  • Mapped types
  • Optional properties
  • Interfaces
  • Interfaces extending other interfaces
  • keyof andtypeof types
  • ReturnType,Omit, etc. types
  • Symbols

Etc. - I haven't though super deeply beyond that. Could you think on what other test cases should happen and fill it all out?

Copy link
ContributorAuthor

@mdm317mdm317Apr 15, 2025
edited
Loading

Choose a reason for hiding this comment

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

The current logic works well for union types, but contains errors when handling intersection types.

Some mapped type has 0 property

  1. Type is a generic type parameter that hasn't been specified yettype U<Type> = {[Property in keyof Type]: 0;};
  2. An object type with potentially unlimited string keys,Record<string, number>
object type0 property0> property
0 propertycheck assignablenon redundant
0 > propertynon redundantcheck assignable

optional property
In typescript type with only the required property a:1 is assignable to type with the same required property plus an optional property b?:1
type T = { a : 1 } & { a : 1, b? : 1}
I've added logic that determines: when typeA is assignable to typeB andB contains no extra optional properties beyondA, thenB is considered redundant.

@JoshuaKGoldbergJoshuaKGoldberg added the awaiting responseIssues waiting for a reply from the OP or another party labelMar 17, 2025
@mdm317
Copy link
ContributorAuthor

Thank you for your review!
I'll try implementing it according to your suggestion.

JoshuaKGoldberg reacted with rocket emoji

@mdm317mdm317 marked this pull request as draftApril 1, 2025 16:56
@mdm317mdm317 marked this pull request as ready for reviewApril 5, 2025 15:52
@mdm317
Copy link
ContributorAuthor

@JoshuaKGoldberg

Hello I have a question about applying rules to our code.
It seems that in our codebase, we are intentionally using overridden types, like in the code below.

exportinterfaceClassDeclarationWithNameextendsClassDeclarationBase{
id:Identifier;
}
/**
* Default-exported class declarations have optional names:
* ```
* export default class {}
* ```
*/
exportinterfaceClassDeclarationWithOptionalNameextendsClassDeclarationBase{
id:Identifier|null;
}
exporttypeClassDeclaration=
|ClassDeclarationWithName
|ClassDeclarationWithOptionalName;

ClassDeclarationWithName is ovveridden by ClassDeclarationWithOptionalName in this union type

|FunctionDeclarationWithName
|FunctionDeclarationWithOptionalName

FunctionDeclarationWithOptionalName is ovveridden by FunctionDeclarationWithName in this union type

In this case, should I remove them, use eslint-disable, or modify the rule itself?

@JoshuaKGoldberg
Copy link
Member

Ha, that's really interesting. Nice find. My instinct is that we should modify thespec.ts files because the union types really are violating the rule - cc @typescript-eslint/triage-team

mdm317 reacted with heart emoji

@mdm317mdm317 marked this pull request as draftApril 9, 2025 17:10
Copy link
ContributorAuthor

@mdm317mdm317 left a comment

Choose a reason for hiding this comment

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

This change was made to applying lint to code.
Let me know if you have any concerns about this adjustment

| FunctionDeclarationWithName
| FunctionDeclarationWithOptionalName;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
FunctionDeclarationWithName| FunctionDeclarationWithOptionalName;
Copy link
ContributorAuthor

@mdm317mdm317Apr 13, 2025
edited
Loading

Choose a reason for hiding this comment

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

Due to Merging Interfaces, it should not be considered as redundant types.
So I added a lint disable comment for the line.

interfaceFunctionDeclarationWithName{
parent:
|TSESTree.BlockStatement
|TSESTree.ExportDefaultDeclaration
|TSESTree.ExportNamedDeclaration

@@ -47,4 +43,5 @@ export type NamedExportDeclarations =
// TODO - breaking change remove this in the next major
export type ExportDeclaration =
| DefaultExportDeclarations
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
| NamedExportDeclarations;
Copy link
ContributorAuthor

@mdm317mdm317Apr 13, 2025
edited
Loading

Choose a reason for hiding this comment

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

As in the comment above, It is because of Merging InterfacesFunctionDeclarationWithName

@@ -244,6 +244,7 @@ export interface ParserServicesBase {
}
export interface ParserServicesNodeMaps {
esTreeNodeToTSNodeMap: ParserWeakMapESTreeToTSNode;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
tsNodeToESTreeNodeMap: ParserWeakMap<TSNode | TSToken, TSESTree.Node>;
Copy link
ContributorAuthor

@mdm317mdm317Apr 13, 2025
edited
Loading

Choose a reason for hiding this comment

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

InTSNode's union types, the code below is overridden. I think modifying it too complex, so I added a lint
disable code.

@@ -49,6 +49,7 @@ export default createRule({
* @returns the name and attribute of the member or null if it's a member not relevant to the rule.
*/
function getMemberMethod(
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
member: Member | MemberDeclaration,
Copy link
ContributorAuthor

@mdm317mdm317Apr 13, 2025
edited
Loading

Choose a reason for hiding this comment

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

Member -> ProgramStatement -> Statement -> ClassDeclarationWithName
MemberDeclaration -> DefaultExportDeclarations -> ClassDeclarationWithOptionalName
ClassDeclarationWithName is overriden byClassDeclarationWithOptionalName
I think modifying it too complex, so I added a lint disable code.

Copy link
ContributorAuthor

@mdm317mdm317 left a comment

Choose a reason for hiding this comment

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

I'd appreciate your feedback

@@ -22,11 +22,11 @@ type IntersectionNever = string | never;
~~~~~ 'never' is overridden by other types in this union type.

type IntersectionBooleanLiteral = boolean & false;
~~~~~~~ boolean is overridden bythefalse in this intersection type.
~~~~~~~ boolean is overridden by false in this intersection type.
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

Can we removethe?

isFunctionOrFunctionType(node.parent.parent)
);
function hasTargetOnlyOptionalProps(
sourceType: ts.ObjectType,
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

Checkint target type contains no extra optional properties beyond sourceType

(sourceTypeProperties.length === 0) !==
(targetTypeProperties.length === 0)
) {
return false;
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

target type is non redundant

object type0 property0> property
0 propertycheck assignablenon redundant
0 > propertynon redundantcheck assignable

@mdm317mdm317 marked this pull request as ready for reviewApril 15, 2025 16:55
@github-actionsgithub-actionsbot removed the awaiting responseIssues waiting for a reply from the OP or another party labelApr 15, 2025
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@JoshuaKGoldbergJoshuaKGoldbergAwaiting requested review from JoshuaKGoldberg

Requested changes must be addressed to merge this pull request.

Assignees
No one assigned
Labels
None yet
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

Enhancement: [no-redundant-type-constituents] Use assignability checking for redundancy checks
3 participants
@mdm317@JoshuaKGoldberg@gen-ip-1

[8]ページ先頭

©2009-2025 Movatter.jp