Skip to content

refactor: remove redundant type assertions in frontend#3258

Merged
arkid15r merged 7 commits intoOWASP:mainfrom
hussainjamal760:fix/sonar-clean-focused
Jan 9, 2026
Merged

refactor: remove redundant type assertions in frontend#3258
arkid15r merged 7 commits intoOWASP:mainfrom
hussainjamal760:fix/sonar-clean-focused

Conversation

@hussainjamal760
Copy link
Contributor

Issue fixed : #3225

Summary
This PR cleans up the frontend codebase by removing redundant type assertions (as) and non-null assertions (!). These assertions were unnecessary because the TypeScript compiler already had sufficient contextual information to infer the correct types.

Changes
Removed unnecessary assertions in the following files:

frontend/src/app/members/[memberKey]/page.tsx

frontend/src/components/CardDetailsPage.tsx

frontend/src/components/ChapterMap.tsx

frontend/src/components/MultiSearch.tsx

frontend/src/components/SingleModuleCard.tsx

frontend/src/components/UserMenu.tsx

frontend/src/hooks/useSearchPage.ts

frontend/src/utils/env.server.ts

Technical Details
Used @typescript-eslint/no-unnecessary-type-assertion and @typescript-eslint/no-extra-non-null-assertion rules to identify redundant code.

Ensured that no logical changes were introduced, only type-level cleanup.

Fixed an issue in ApiKeysPage.test.tsx where a required cast was accidentally flagged as redundant.

Verification Results
Backend Tests: Passed (Coverage: 83.83%)

Frontend Tests: Passed (make test-frontend-unit)

Linting: All checks passed locally via make lint-frontend and pre-commit.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 8, 2026

Summary by CodeRabbit

  • Refactor
    • Simplified type handling and optional chaining across several UI components, standardized session usage and event handling, and removed unnecessary type assertions—behavior unchanged but code is clearer and more robust.
  • Chores
    • Made GitHub authentication environment variables optional so the app safely handles missing credentials at runtime.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Removed unnecessary TypeScript casts and non‑null assertions across multiple frontend files, replacing explicit assertions with type inference or optional chaining; made two GitHub env vars possibly undefined. No control flow or exported/public signatures changed.

Changes

Cohort / File(s) Summary
Member key / params casts
frontend/src/app/members/[memberKey]/page.tsx
Removed as string casts when passing memberKey to fetchHeatmapData and setUsername.
Search & pagination typings
frontend/src/components/MultiSearch.tsx, frontend/src/hooks/useSearchPage.ts
Removed explicit Event[] cast and an unnecessary assertion when updating totalPages; rely on inferred types.
Admin/login comparisons
frontend/src/components/CardDetailsPage.tsx, frontend/src/components/SingleModuleCard.tsx
Replaced casted session/data accesses with a cached session variable and/or optional chaining for user login comparisons; adjusted conditional rendering usage accordingly.
Event handler typing
frontend/src/components/ChapterMap.tsx
Removed explicit MouseEvent cast for e.originalEvent, using e.originalEvent directly to derive relatedTarget.
Optional chaining for session
frontend/src/components/UserMenu.tsx
Replaced ExtendedSession type assertion with optional chaining (session?.user?.isLeader) and removed the ExtendedSession import.
Env var nullability
frontend/src/utils/env.server.ts
Removed non‑null assertions (!) from GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET, changing their types to `string

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • arkid15r
  • kasya
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: removing redundant type assertions throughout the frontend codebase.
Description check ✅ Passed The description is clearly related to the changeset, providing issue reference, summary of changes, technical approach, and verification results.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b78321 and 6d71f93.

📒 Files selected for processing (1)
  • frontend/src/components/CardDetailsPage.tsx
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: rudransh-shrivastava
Repo: OWASP/Nest PR: 2178
File: frontend/src/app/snapshots/[id]/page.tsx:0-0
Timestamp: 2025-09-21T17:04:48.154Z
Learning: User rudransh-shrivastava confirmed that suggested type safety improvements during Apollo Client migration were no longer relevant, reinforcing their preference to keep migration PRs focused on core migration changes rather than additional improvements.
📚 Learning: 2025-07-13T11:34:31.823Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/page.tsx:14-14
Timestamp: 2025-07-13T11:34:31.823Z
Learning: In the Next.js frontend mentorship application, there are two distinct types for authentication-related data: ExtendedSession for useSession hook (containing accessToken and user.login properties) and UserRolesData for useUserRoles hook (containing currentUserRoles.roles array). The correct access pattern for GitHub username is `(session as ExtendedSession)?.user?.login`.

Applied to files:

  • frontend/src/components/CardDetailsPage.tsx
📚 Learning: 2025-06-20T16:12:59.256Z
Learnt from: ahmedxgouda
Repo: OWASP/Nest PR: 1633
File: frontend/src/components/HealthMetrics.tsx:30-30
Timestamp: 2025-06-20T16:12:59.256Z
Learning: In the DetailsCard component (frontend/src/components/CardDetailsPage.tsx), there's a safety check that ensures HealthMetrics component is only rendered when healthMetricsData exists and has at least one element: `healthMetricsData && healthMetricsData.length > 0`. This makes accessing data[0] safe within the HealthMetrics component.

Applied to files:

  • frontend/src/components/CardDetailsPage.tsx
🔇 Additional comments (2)
frontend/src/components/CardDetailsPage.tsx (2)

102-102: LGTM! Type assertion appropriately centralizes session typing.

This change successfully consolidates the type assertion at the point of declaration. By typing session once as ExtendedSession | null, the downstream code (like line 129) can access session?.user?.login without redundant type assertions. This is cleaner and more maintainable than scattering assertions throughout the component.


129-131: Excellent cleanup! Redundant type assertions successfully removed.

The refactored code correctly removes the unnecessary as ExtendedSession and as string assertions by leveraging the typed session variable from line 102. The logic remains identical—if no session exists, the comparison evaluates to false and EntityActions won't render. TypeScript can now infer the types without explicit assertions.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 8, 2026
kasya
kasya previously requested changes Jan 9, 2026
Copy link
Collaborator

@kasya kasya left a comment

Choose a reason for hiding this comment

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

Hi @hussainjamal760 !

Thanks for updating these.
Could you also resolve Sonar issue that was introduced in this PR?

Image

@kasya
Copy link
Collaborator

kasya commented Jan 9, 2026

Hm... it now says there are no issues 😅

@hussainjamal760 there are still checks failing, so please make sure everything is green and ready for review.
Run make check-test locally, address all found issues. This runs both tests and linters and it is required.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 9, 2026
@hussainjamal760
Copy link
Contributor Author

@kasya thanks for the update. I’ve resolved the issue and have now pushed a new commit with all checks passing. I ran make check-test locally and ensured that all tests and linters pass,

Screenshot 2026-01-09 035622 Screenshot 2026-01-09 035709 Screenshot 2026-01-09 070028

Please let me know if anything else needs to be addressed.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
frontend/src/components/CardDetailsPage.tsx (2)

102-104: New ExtendedSession cast slightly conflicts with PR goal; consider typing useSession instead.

const session = data as ExtendedSession | null reintroduces a type assertion. If the repo supports it, prefer typing via NextAuth session module augmentation (or useSession<...>() if available) so the compiler “knows” user.login without as. Based on learnings, user.login access is the intended pattern for ExtendedSession.

Possible direction (depends on repo + next-auth typing support)
-  const { data } = useSession()
-  const session = data as ExtendedSession | null
+  const { data: session } = useSession() // ideally already typed as ExtendedSession | null via module augmentation

128-132: Cleaner module-admin check; consider extracting to a boolean for readability.

The admins?.some((admin) => admin.login === session?.user?.login) is a nice improvement over forcing as stringundefined simply won’t match. A small readability win would be extracting const isModuleAdmin = ... before JSX to reduce nesting.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6dc1961 and 5b78321.

📒 Files selected for processing (1)
  • frontend/src/components/CardDetailsPage.tsx
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: rudransh-shrivastava
Repo: OWASP/Nest PR: 2178
File: frontend/src/app/snapshots/[id]/page.tsx:0-0
Timestamp: 2025-09-21T17:04:48.154Z
Learning: User rudransh-shrivastava confirmed that suggested type safety improvements during Apollo Client migration were no longer relevant, reinforcing their preference to keep migration PRs focused on core migration changes rather than additional improvements.
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/api/auth/[...nextauth]/route.ts:13-25
Timestamp: 2025-08-10T11:08:47.258Z
Learning: In the OWASP Nest codebase (frontend/src/app/api/auth/[...nextauth]/route.ts), input validation and string trimming for authentication-related queries like `isProjectLeader` and `isMentor` are handled in the backend rather than the frontend. The backend is responsible for sanitizing and validating input parameters.
📚 Learning: 2025-07-13T11:34:31.823Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/page.tsx:14-14
Timestamp: 2025-07-13T11:34:31.823Z
Learning: In the Next.js frontend mentorship application, there are two distinct types for authentication-related data: ExtendedSession for useSession hook (containing accessToken and user.login properties) and UserRolesData for useUserRoles hook (containing currentUserRoles.roles array). The correct access pattern for GitHub username is `(session as ExtendedSession)?.user?.login`.

Applied to files:

  • frontend/src/components/CardDetailsPage.tsx
📚 Learning: 2025-06-20T16:12:59.256Z
Learnt from: ahmedxgouda
Repo: OWASP/Nest PR: 1633
File: frontend/src/components/HealthMetrics.tsx:30-30
Timestamp: 2025-06-20T16:12:59.256Z
Learning: In the DetailsCard component (frontend/src/components/CardDetailsPage.tsx), there's a length check before rendering HealthMetrics: `healthMetricsData.length > 0`. This ensures that when HealthMetrics is rendered, the data array has at least one element, making accessing data[0] safe within the HealthMetrics component.

Applied to files:

  • frontend/src/components/CardDetailsPage.tsx
📚 Learning: 2025-06-20T16:12:59.256Z
Learnt from: ahmedxgouda
Repo: OWASP/Nest PR: 1633
File: frontend/src/components/HealthMetrics.tsx:30-30
Timestamp: 2025-06-20T16:12:59.256Z
Learning: In the DetailsCard component (frontend/src/components/CardDetailsPage.tsx), there's a safety check that ensures HealthMetrics component is only rendered when healthMetricsData exists and has at least one element: `healthMetricsData && healthMetricsData.length > 0`. This makes accessing data[0] safe within the HealthMetrics component.

Applied to files:

  • frontend/src/components/CardDetailsPage.tsx

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 9, 2026
@hussainjamal760
Copy link
Contributor Author

@kasya . I’ve resolved the sonar issue that was introduced in this PR : https://sonarcloud.io/project/issues?pullRequest=3258&open=AZugeER74ckZxBvSsqH4&id=OWASP_Nest

and have now pushed a new commit

@hussainjamal760 hussainjamal760 requested a review from kasya January 9, 2026 02:21
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 9, 2026
@arkid15r arkid15r enabled auto-merge January 9, 2026 20:21
@sonarqubecloud
Copy link

sonarqubecloud bot commented Jan 9, 2026

@arkid15r arkid15r dismissed kasya’s stale review January 9, 2026 23:34

Sonar looks happy now

@arkid15r arkid15r added this pull request to the merge queue Jan 9, 2026
Merged via the queue into OWASP:main with commit 217088e Jan 9, 2026
27 checks passed
hussainjamal760 added a commit to hussainjamal760/Nest that referenced this pull request Jan 14, 2026
* refactor: remove redundant type assertions in frontend

* resolved line-ending/formatting issues across backend and frontend files to pass make check

* refactor: remove redundant type assertion for ExtendedSession

* type assertion in DetailsCard to satisfy linting and PR feedback.

---------

Co-authored-by: Kate Golovanova <kate@kgthreads.com>
Co-authored-by: Arkadii Yakovets <2201626+arkid15r@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove unnecessary type assertion as the receiver accepts the original expression type

3 participants

Comments