Repository navigation
Mark enum members referenced in other members' initializers as used - #2338
Conversation
commit: |
webpro
left a comment
There was a problem hiding this comment.
Thanks! This reproduces on main and is fixed here: with only Permission.ReadWrite used, Read and Write are reported, and --fix leaves ReadWrite = Read | Write, which fails to compile with TS2304. The test fails without the source change. Skipping literal initializers and building the name map only when needed keeps this cheap.
Known gap: a member that only an unused member references is now kept, so when the walk misses one of its own dependencies, --fix removes that dependency and breaks the build, where main removes the whole unused chain. With only E.Used used, export enum E { Used = 0, A = 1, B = E["A"] + 1, C = B + 1 } keeps B and removes A and C. The same happens with a type annotation in the initializer (B = ((value: A) => value)(1)), an auto-numbered member after a string member (Used = "used", A = 1, B, C = B), A declared in a merged enum declaration, and an escaped member name ("\u0041" = 1, B = A + 1). These shapes are rare, and we don't want to add complexity for them now.
|
ð This pull request is included in v6.45.1. See Release 6.45.1 for release notes. Using Knip in a commercial project? Please consider becoming a sponsor. |
Since v6, an enum member that is only referenced by its bare name in another member's initializer is reported as unused:
With only
Permission.ReadWriteused elsewhere,ReadandWriteare reported, andknip --fixremoves them, which breaks the build (TS2304: Cannot find name 'Read'). v5.88.1 reports nothing. The qualified form (Permission.Read | Permission.Write) already works.extractEnumMembersnow walks non-literal initializers and marks members referenced by name as used in the file. Property names of non-computed member access (Math.max) are skipped, and literal initializers are not walked.Test: extended the
enum-membersfixture with a flags enum. Without the fix the existing test reports 4 members instead of 2.