Content-Length: 783596 | pFad | http://github.com/typescript-eslint/typescript-eslint/pull/10744

CC feat(eslint-plugin): [no-redundant-type-constituents] use assignability checking for redundancy checks by mdm317 · Pull Request #10744 · typescript-eslint/typescript-eslint · GitHub
Skip to content

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 41 commits into
base: main
Choose a base branch
from

Conversation

mdm317
Copy link
Contributor

@mdm317 mdm317 commented Jan 29, 2025

PR Checklist

Overview

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

This feature seems to overlap with this rule no-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's Excess 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.
For A | B, i checks if A and B 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 if A is assignable to B 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 on https://opencollective.com/typescript-eslint.

Copy link

netlify bot commented Jan 29, 2025

Deploy Preview for typescript-eslint ready!

Name Link
🔨 Latest commit e240759
🔍 Latest deploy log https://app.netlify.com/sites/typescript-eslint/deploys/67fe8a91cd0d740008558ccf
😎 Deploy Preview https://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 your Netlify site configuration.

Copy link

nx-cloud bot commented Jan 29, 2025

View your CI Pipeline Execution ↗ for commit e240759.

Command Status Duration Result
nx typecheck ast-spec ✅ Succeeded <1s View ↗
nx run-many --target=build --exclude website --... ✅ Succeeded 3s View ↗
nx run-many --target=clean ✅ Succeeded 11s View ↗

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

Copy link

codecov bot commented Jan 29, 2025

Codecov Report

Attention: Patch coverage is 97.05215% with 13 lines in your changes missing coverage. Please review.

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

Files with missing lines Patch % Lines
...plugin/src/rules/no-redundant-type-constituents.ts 97.48% 10 Missing and 1 partial ⚠️
...escript-estree/src/semantic-or-syntactic-errors.ts 0.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     
Flag Coverage Δ
unittest 90.81% <97.05%> (-0.01%) ⬇️

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

Files with missing lines Coverage Δ
...t-plugin/src/rules/adjacent-overload-signatures.ts 100.00% <ø> (ø)
...ages/eslint-plugin/src/rules/no-unsafe-argument.ts 93.24% <100.00%> (ø)
...nt-plugin/src/rules/related-getter-setter-pairs.ts 100.00% <ø> (ø)
...escript-estree/src/semantic-or-syntactic-errors.ts 2.32% <0.00%> (ø)
...plugin/src/rules/no-redundant-type-constituents.ts 97.45% <97.48%> (-0.20%) ⬇️

... and 1 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
Contributor Author

mdm317 commented Mar 3, 2025

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.

@mdm317 mdm317 marked this pull request as ready for review March 5, 2025 19:03
Copy link
Member

@JoshuaKGoldberg JoshuaKGoldberg 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! 🙌

Copy link
Member

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 and typeof 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
Contributor Author

@mdm317 mdm317 Apr 15, 2025

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 yet type U<Type> = {[Property in keyof Type]: 0;};
  2. An object type with potentially unlimited string keys, Record<string, number>
object type 0 property 0> property
0 property check assignable non redundant
0 > property non redundant check 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 type A is assignable to type B and B contains no extra optional properties beyond A, then B is considered redundant.

@JoshuaKGoldberg JoshuaKGoldberg added the awaiting response Issues waiting for a reply from the OP or another party label Mar 17, 2025
@mdm317
Copy link
Contributor Author

mdm317 commented Mar 20, 2025

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

@mdm317 mdm317 marked this pull request as draft April 1, 2025 16:56
@mdm317 mdm317 marked this pull request as ready for review April 5, 2025 15:52
@mdm317
Copy link
Contributor Author

mdm317 commented Apr 5, 2025

@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.

export interface ClassDeclarationWithName extends ClassDeclarationBase {
id: Identifier;
}
/**
* Default-exported class declarations have optional names:
* ```
* export default class {}
* ```
*/
export interface ClassDeclarationWithOptionalName extends ClassDeclarationBase {
id: Identifier | null;
}
export type ClassDeclaration =
| 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 the spec.ts files because the union types really are violating the rule - cc @typescript-eslint/triage-team

@mdm317 mdm317 marked this pull request as draft April 9, 2025 17:10
Copy link
Contributor Author

@mdm317 mdm317 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
Contributor Author

@mdm317 mdm317 Apr 13, 2025

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.

interface FunctionDeclarationWithName {
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
Contributor Author

@mdm317 mdm317 Apr 13, 2025

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 Interfaces FunctionDeclarationWithName

@@ -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
Contributor Author

@mdm317 mdm317 Apr 13, 2025

Choose a reason for hiding this comment

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

In TSNode '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
Contributor Author

@mdm317 mdm317 Apr 13, 2025

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 by ClassDeclarationWithOptionalName
I think modifying it too complex, so I added a lint disable code.

Copy link
Contributor Author

@mdm317 mdm317 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 by the false in this intersection type.
~~~~~~~ boolean is overridden by false in this intersection type.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Can we remove the?

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

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
Contributor Author

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 type 0 property 0> property
0 property check assignable non redundant
0 > property non redundant check assignable

@mdm317 mdm317 marked this pull request as ready for review April 15, 2025 16:55
@mdm317 mdm317 requested a review from JoshuaKGoldberg April 15, 2025 16:55
@github-actions github-actions bot removed the awaiting response Issues waiting for a reply from the OP or another party label Apr 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhancement: [no-redundant-type-constituents] Use assignability checking for redundancy checks
3 participants








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/typescript-eslint/typescript-eslint/pull/10744

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy