Skip to content

Strict null checks#852

Merged
CodeWithCJ merged 5 commits intoCodeWithCJ:mainfrom
Sim-sat:strict-null-checks
Mar 6, 2026
Merged

Strict null checks#852
CodeWithCJ merged 5 commits intoCodeWithCJ:mainfrom
Sim-sat:strict-null-checks

Conversation

@Sim-sat
Copy link
Contributor

@Sim-sat Sim-sat commented Mar 6, 2026

Description

Adds and fixes the following typescript rules

  • strict null checks
  • noUncheckedIndexedAccess
  • noPropertyAccessFromIndexSignature
  • enabled strict mode

This will significantly increase runtime safety and preventing almost all runtime errors. This also enables use to use zod validation since it requires strict typescript.

There were about 200 errors each so the pr is quite large. The logic was not changed.

Related Issue

PR type [ ] Issue [ ] New Feature [ ] Documentation
Linked Issue: #

Checklist

Please check all that apply:

  • [MANDATORY for new feature] Alignment: I have raised a GitHub issue and it was reviewed/approved by maintainers
  • Tests: I have included automated tests for my changes.
  • [MANDATORY for UI changes] Screenshots: I have attached "Before" vs "After" screenshots below.
  • [MANDATORY for Frontend changes] Quality: I have run pnpm run validate (especially for Frontend).
  • Translations: I have only updated the English (en) translation file (if applicable).
  • Architecture: My code follows the existing architecture standards.
  • Database Security: I have updated rls_policies.sql for any new user-specific tables.
  • [MANDATORY - ALL] Integrity & License: I certify this is my own work, free of malicious code(phishing, malware, etc.) and I agree to the License terms.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the frontend's type safety by enabling TypeScript's strict mode and enforcing stricter null and property access checks. The changes primarily involve explicit handling of potentially null or undefined values throughout the codebase, ensuring more robust and predictable code behavior without altering any existing application logic. This extensive refactoring addresses numerous type-related issues, making the codebase more maintainable and less prone to common programming errors.

Highlights

  • TypeScript Strictness: Enabled TypeScript's strict mode and introduced new strict rules such as strictNullChecks, noUncheckedIndexedAccess, and noPropertyAccessFromIndexSignature across the frontend codebase. This involved explicitly handling potential null or undefined values using optional chaining (?.), nullish coalescing (??), and explicit type assertions.
  • Improved Type Safety: Refactored numerous function parameters, state variables, and object properties to correctly reflect their nullable or optional nature, enhancing overall type safety and reducing potential runtime errors. This includes updates to useState hooks, API call parameters, and data processing logic.
  • Codebase Refinement: Addressed approximately 200 TypeScript errors resulting from the new strict rules, primarily by adding explicit null/undefined checks and providing default values where appropriate. The pull request description confirms that no functional logic was changed as part of these type safety improvements.
  • Interface and Type Definition Updates: Introduced new interfaces like ReleaseInfo, ExerciseSearchParams, MealParams, WorkoutSearchParams, OnboardingData, Sex, FailedEntry, ImportError, Zones, NutrientTotals, and PersonalRecordsMap to provide more precise type definitions for various data structures and API payloads.
Changelog
  • SparkyFitnessFrontend/src/App.tsx
    • Imported ReleaseInfo type for new release dialogs.
    • Updated latestRelease state to explicitly allow ReleaseInfo | null.
  • SparkyFitnessFrontend/src/api/Chatbot/Chatbot_FoodHandler.ts
    • Implemented optional chaining for foodOptions access.
    • Updated error message for invalid option index.
    • Applied nullish coalescing for quantity in calorie calculations.
  • SparkyFitnessFrontend/src/api/Chatbot/Chatbot_MeasurementHandler.ts
    • Initialized ApiError variables as empty objects instead of null.
    • Added type assertions for caught errors to ApiError.
  • SparkyFitnessFrontend/src/api/Chatbot/sparkyChatService.ts
    • Added nullish coalescing for jsonString and parsedResponse.response.
    • Applied nullish coalescing for foodName and unit in callAIForFoodOptions.
    • Refactored date extraction to include null checks for destructured parts.
  • SparkyFitnessFrontend/src/api/Exercises/exerciseEntryService.ts
    • Added nullish coalescing for properties within exercise_snapshot and activity_details to ensure non-null values.
  • SparkyFitnessFrontend/src/api/Exercises/exerciseSearchService.ts
    • Introduced ExerciseSearchParams and ExternalExerciseSearchParams interfaces.
    • Updated API parameter types to use new search interfaces.
  • SparkyFitnessFrontend/src/api/Exercises/workoutPresets.ts
    • Introduced WorkoutSearchParams interface for search parameters.
  • SparkyFitnessFrontend/src/api/Foods/enhancedCustomFoodFormService.ts
    • Added a null check for primaryVariant when creating new food.
    • Updated variantErrors initialization to use empty strings instead of null.
    • Added null checks and error logging for variantToDuplicate, currentVariant, and originalVariant.
    • Changed handleSubmit event type from React.FormEvent to React.SubmitEvent.
  • SparkyFitnessFrontend/src/api/Foods/fatSecret.ts
    • Applied nullish coalescing for parseFloat arguments and optional chaining for servingMatch[2].
  • SparkyFitnessFrontend/src/api/Foods/mealPlanTemplate.ts
    • Modified updateMealPlanTemplate to use templateData.id instead of a separate templateId parameter.
  • SparkyFitnessFrontend/src/api/Foods/meals.ts
    • Introduced MealParams interface for meal API parameters.
    • Made mealId optional in getMealById function signature.
  • SparkyFitnessFrontend/src/api/Foods/nutrionix.ts
    • Imported NutritionixItem type.
    • Added null checks for food objects retrieved from API responses.
    • Updated brand property to default to an empty string instead of null.
    • Added nullish coalescing for item.id in nutritionixBrandedNutrientsOptions.
  • SparkyFitnessFrontend/src/api/Onboarding/onboarding.ts
    • Moved OnboardingData interface to a dedicated types/onboarding file and imported it.
  • SparkyFitnessFrontend/src/api/Settings/aiServiceSettingsService.ts
    • Changed the return value from null to { auto_clear_history: '' } for 404 responses in getPreferences.
  • SparkyFitnessFrontend/src/api/api.ts
    • Removed generic type T from apiCall and explicitly set return type to Promise<any>.
    • Removed as unknown as T type assertions for returning empty arrays or blob responses.
  • SparkyFitnessFrontend/src/api/general.ts
    • Imported ReleaseInfo type.
    • Updated return type of getLatestGithubRelease to Promise<ReleaseInfo>.
  • SparkyFitnessFrontend/src/api/keys/meals.ts
    • Made mealId optional in mealKeys.one function signature.
  • SparkyFitnessFrontend/src/components/AppSetup.tsx
    • Imported ReleaseInfo type.
    • Updated setLatestRelease prop type to handle ReleaseInfo | null.
  • SparkyFitnessFrontend/src/components/DraggableChatbotButton.tsx
    • Added null checks for e.touches[0] before accessing client coordinates.
  • SparkyFitnessFrontend/src/components/ExerciseHistoryDisplay.tsx
    • Added optional chaining to history.length.
    • Added a null check for history before rendering CardContent.
    • Applied nullish coalescing for set.weight in convertWeight.
  • SparkyFitnessFrontend/src/components/FoodSearch/BarcodeScanner.tsx
    • Added optional chaining and nullish coalescing for videoDevices[0].deviceId.
    • Implemented null checks for touch objects in touch event handlers.
  • SparkyFitnessFrontend/src/components/FoodSearch/CustomFoodForm.tsx
    • Imported error logging utility.
    • Included loggingLevel from usePreferences.
    • Initialized variantErrors with empty strings.
    • Added null checks for variant objects in duplicateVariant, handleVariantChange, and saveFood.
    • Updated handleSubmit event type to React.SubmitEvent.
  • SparkyFitnessFrontend/src/components/FoodSearch/FoodResultCard.tsx
    • Imported useActiveUser and removed activeUserId prop, now retrieved from context.
  • SparkyFitnessFrontend/src/components/FoodSearch/FoodSearch.tsx
    • Removed useActiveUser import.
    • Applied nullish coalescing for p.base_url in searchMealieOptions and searchTandoorOptions.
    • Added null checks for searchHandler and searchProviderId.
    • Added nullish coalescing for item.id in nutritionixBrandedNutrientsOptions.
    • Added type assertion for nutrientData in handleFatSecretEdit.
  • SparkyFitnessFrontend/src/components/FoodUnitSelector.tsx
    • Added null checks for firstCombinedVariant and variant.id.
  • SparkyFitnessFrontend/src/components/MealBuilder.tsx
    • Added optional chaining to onSave() calls.
    • Applied nullish coalescing to totals[key] in total calculations.
  • SparkyFitnessFrontend/src/components/MealPercentageManager.tsx
    • Added null checks for mealToAdjust and value in slider change handlers.
  • SparkyFitnessFrontend/src/components/NewReleaseDialog.tsx
    • Defined and utilized ReleaseInfo interface for release information.
  • SparkyFitnessFrontend/src/components/Onboarding/DietApproach.tsx
    • Added null checks for template before accessing its properties.
    • Applied nullish coalescing for value in macro value change handlers.
  • SparkyFitnessFrontend/src/components/Onboarding/OnBoarding.tsx
    • Added optional chaining to user.activeUserId.
    • Implemented conditional rendering for OnBoardingForm based on data availability.
  • SparkyFitnessFrontend/src/components/Onboarding/OnBoardingForm.tsx
    • Imported OnboardingData and Sex from types/onboarding.
    • Updated FormData type to OnboardingData.
    • Set default values for mealsPerDay and addBurnedCalories.
  • SparkyFitnessFrontend/src/components/Onboarding/OnBoardingSteps.tsx
    • Updated FormData type to OnboardingData.
  • SparkyFitnessFrontend/src/components/Onboarding/PersonalPlan.tsx
    • Imported useAuth and OnboardingData.
    • Updated FormData type to OnboardingData.
    • Added null checks for user.activeUserId and updatedPlan.
    • Changed undefined to 0 for numeric form fields when empty.
  • SparkyFitnessFrontend/src/components/Onboarding/PersonalPlanHeader.tsx
    • Imported OnboardingData.
    • Added optional chaining to plan.bmr.
  • SparkyFitnessFrontend/src/constants/dietTemplates.ts
    • Updated getDietTemplate return type to DietTemplate | undefined.
  • SparkyFitnessFrontend/src/contexts/PreferencesContext.tsx
    • Initialized dateToFormat and added null checks during date parsing.
  • SparkyFitnessFrontend/src/contexts/WaterContainerContext.tsx
    • Updated activeContainer type to include undefined.
    • Added null check for firstContainer before setting primary.
  • SparkyFitnessFrontend/src/hooks/AI/useSparkyChat.ts
    • Imported MessageMetadata.
    • Applied nullish coalescing for metadata.
    • Updated lastBotMessageMetadata type to MessageMetadata.
  • SparkyFitnessFrontend/src/hooks/CheckIn/useCheckIn.ts
    • Updated userId parameter to allow null.
    • Added enabled option to useQuery and non-null assertions.
  • SparkyFitnessFrontend/src/hooks/Diary/useDailyProgress.ts
    • Applied nullish coalescing for user?.id in userKeys.profile.
  • SparkyFitnessFrontend/src/hooks/Foods/useMealplanTemplate.ts
    • Updated userId parameter to allow null.
    • Added enabled option to useQuery and non-null assertions.
    • Simplified updateMealPlanTemplate call.
  • SparkyFitnessFrontend/src/hooks/Foods/useMeals.ts
    • Made mealId optional in mealViewOptions.
  • SparkyFitnessFrontend/src/hooks/Onboarding/useOnboarding.ts
    • Imported OnboardingData from types/onboarding.
  • SparkyFitnessFrontend/src/hooks/Reports/useReports.ts
    • Updated userId parameter to allow null.
    • Added enabled option to useQuery and non-null assertions.
    • Changed undefined to 0 for measurement values in select function.
  • SparkyFitnessFrontend/src/hooks/Settings/useProfile.ts
    • Updated url parameter to allow undefined.
    • Used non-null assertions for url and userId.
    • Changed userId parameter in mutations to be non-optional.
  • SparkyFitnessFrontend/src/hooks/Settings/useWaterContainers.ts
    • Updated userId parameter to allow undefined.
  • SparkyFitnessFrontend/src/lib/scannerEngines/ZxingEngine.ts
    • Added a null check for this.currentDeviceId before initiating barcode scanning.
  • SparkyFitnessFrontend/src/pages/Admin/BackupSettingsForm.tsx
    • Added null checks for hours and minutes before setting date components.
  • SparkyFitnessFrontend/src/pages/Admin/GlobalAISettings.tsx
    • Changed null to empty string '' for custom_url and model_name defaults.
  • SparkyFitnessFrontend/src/pages/Admin/OidcSettings.tsx
    • Added optional chaining to providers.map.
  • SparkyFitnessFrontend/src/pages/Auth/Auth.tsx
    • Initialized mfaChallengeProps state as undefined.
    • Added null checks for provider and provider.id.
    • Updated handleSignUp and handleSignIn event types to React.SubmitEvent.
    • Added null check for mfaChallengeProps before spreading.
  • SparkyFitnessFrontend/src/pages/Chat/SparkyChatInterface.tsx
    • Applied nullish coalescing for todayStr.
    • Changed lastBotMessageMetadata default from null to {}.
  • SparkyFitnessFrontend/src/pages/CheckIn/HomeDashboardFasting.tsx
    • Reordered handleEndFast parameters to make weight and mood optional.
  • SparkyFitnessFrontend/src/pages/CheckIn/MoodMeter.tsx
    • Applied nullish coalescing for vals[0] in onValueChange.
  • SparkyFitnessFrontend/src/pages/CheckIn/SleepEntrySection.tsx
    • Updated handleSleepSubmit event type to React.SubmitEvent.
    • Changed id: undefined to id: '' for new sleep events.
    • Added null checks for session before updating sleep sessions.
    • Applied nullish coalescing for entry.sleep_score.
  • SparkyFitnessFrontend/src/pages/CheckIn/SleepTimelineEditor.tsx
    • Added a null check for lastEvent in the segment reduction logic.
  • SparkyFitnessFrontend/src/pages/Diary/CopyFoodEntryDialog.tsx
    • Added optional chaining to availableMealTypes array access.
  • SparkyFitnessFrontend/src/pages/Diary/Diary.tsx
    • Added optional chaining to availableMealTypes.find.
    • Added null check for currentUserId in handleFoodUnitSelect.
    • Applied optional chaining and nullish coalescing for availableMealTypes and foodEntryMeals.
  • SparkyFitnessFrontend/src/pages/Diary/EditExerciseEntryDialog.tsx
    • Changed imageUrl state type to string and default to empty string.
    • Changed null to undefined for value in handleSetChange.
    • Added null checks for lastSet and setToDuplicate.
    • Changed null to 0 for distance and avg_heart_rate when inputs are empty.
  • SparkyFitnessFrontend/src/pages/Diary/EditFoodEntryDialog.tsx
    • Updated handleSubmit event type to SubmitEvent.
    • Added null check for variant.id before rendering SelectItem.
  • SparkyFitnessFrontend/src/pages/Diary/ExerciseCard.tsx
    • Added null checks for currentExercise before setting state.
    • Added null check for cal before isNaN check.
    • Applied optional chaining to exerciseEntries array access.
  • SparkyFitnessFrontend/src/pages/Diary/ExerciseEntryDisplay.tsx
    • Added null check for set.weight before Number.isFinite check.
  • SparkyFitnessFrontend/src/pages/Diary/ExercisePlaybackModal.tsx
    • Applied nullish coalescing for instructions[currentInstructionIndex].
  • SparkyFitnessFrontend/src/pages/Diary/ExerciseSortableItems.tsx
    • Changed null to undefined for newValue in handleSetChange.
  • SparkyFitnessFrontend/src/pages/Diary/LogExerciseEntryDialog.tsx
    • Added null checks for currentSet, lastSet, and setToDuplicate.
    • Changed null to 0 for distance and avg_heart_rate when inputs are empty.
  • SparkyFitnessFrontend/src/pages/Diary/MiniNutritionTrends.tsx
    • Added null checks for payload[0] and label in CustomTooltip.
  • SparkyFitnessFrontend/src/pages/Diary/NutrientsGrid.tsx
    • Updated baseVariant prop type to allow undefined.
  • SparkyFitnessFrontend/src/pages/Diary/WaterIntake.tsx
    • Added optional chaining to user.id.
    • Added null check for userId before calling updateWaterIntake.
  • SparkyFitnessFrontend/src/pages/Exercises/AddExerciseDialog.tsx
    • Added null checks for draggedFile and draggedUrl before array splicing.
  • SparkyFitnessFrontend/src/pages/Exercises/AddWorkoutPlanDialog.tsx
    • Updated value type in handleSetChange to WorkoutPresetSet[keyof WorkoutPresetSet].
    • Added null checks for lastSet, setToDuplicate, sourceItem.
    • Applied optional chaining and nullish coalescing for various properties.
    • Changed null to empty string '' for end_date.
    • Added null checks for exercise and sourceMode in onExerciseAdded.
  • SparkyFitnessFrontend/src/pages/Exercises/ExerciseEntryHistoryImportCSV.tsx
    • Removed isObject import.
    • Added optional chaining to results.errors[0]?.message.
    • Added optional chaining to dropdownOptions access.
    • Defined FailedEntry and ImportError interfaces for better error handling.
    • Used type assertion for importError.
  • SparkyFitnessFrontend/src/pages/Exercises/ExerciseImportCSV.tsx
    • Added name: string to ExerciseCSVData interface.
    • Added optional chaining to array split operations and parsedHeaders.forEach.
    • Added null checks for values and headers.
    • Updated handleSubmit event type to React.SubmitEvent.
  • SparkyFitnessFrontend/src/pages/Exercises/ExerciseSearch.tsx
    • Added null check for selectedProviderType in handleAddExternalExercise.
    • Added null check for provider before accessing properties.
    • Applied nullish coalescing for exercise.instructions.
  • SparkyFitnessFrontend/src/pages/Exercises/Exercises.tsx
    • Added optional chaining to user.id.
    • Applied nullish coalescing for shouldForce.
    • Added null checks for draggedItem before array splicing.
  • SparkyFitnessFrontend/src/pages/Exercises/WorkoutPlansManager.tsx
    • Added optional chaining to user.id.
    • Added optional chaining to plans.find.
  • SparkyFitnessFrontend/src/pages/Exercises/WorkoutPresetForm.tsx
    • Added null check for exercise in handleAddExercise.
    • Updated value type in handleSetChange.
    • Added null checks for lastSet, setToDuplicate, and exercise.
    • Added null check for set.weight before convertWeight.
  • SparkyFitnessFrontend/src/pages/Exercises/WorkoutPresetsManager.tsx
    • Added null check for today before logging workout preset.
  • SparkyFitnessFrontend/src/pages/Fasting/EndFastDialog.tsx
    • Reordered onEnd prop parameters to make weight and mood optional.
    • Changed undefined to new Date() for start and end in handleConfirm.
  • SparkyFitnessFrontend/src/pages/Foods/FoodImportFromCSV.tsx
    • Added optional chaining to array split operations and parsedHeaders.forEach.
    • Added null checks for values, fileHeaders, and headers.
  • SparkyFitnessFrontend/src/pages/Foods/Foods.tsx
    • Applied nullish coalescing for entry_date.
    • Added optional chaining to foodData.foods array access.
  • SparkyFitnessFrontend/src/pages/Foods/MealPlanCalendar.tsx
    • Applied nullish coalescing for currentClientDate.
    • Added optional chaining to templates.find.
  • SparkyFitnessFrontend/src/pages/Foods/MealPlanTemplateForm.tsx
    • Added optional chaining to template.assignments.
    • Added null checks for assignmentAtIndex.
    • Added null checks for startDate and endDate before comparison.
  • SparkyFitnessFrontend/src/pages/Goals/GoalPresetDialog.tsx
    • Added null check for formData.
    • Applied nullish coalescing for CENTRAL_NUTRIENT_CONFIG[m]?.label.
  • SparkyFitnessFrontend/src/pages/Goals/WeeklyGoalPlanDialog.tsx
    • Added null check for preset.id before rendering SelectItem.
  • SparkyFitnessFrontend/src/pages/Reports/ActivityReportLapTable.tsx
    • Added optional chaining and nullish coalescing for acc[acc.length - 1] properties.
    • Added type assertion for ProcessedLap[] in reduce.
    • Added null checks for minutes and seconds in parsePaceToSeconds.
    • Applied nullish coalescing for lap.averageSpeed.
    • Added null check for lastLap.
    • Added optional chaining to processedLaps[processedLaps.length - 1]?.cumulativeDistance.
  • SparkyFitnessFrontend/src/pages/Reports/ActivityReportVisualizer.tsx
    • Applied nullish coalescing for metric.metrics[timestampIndex] and distanceIndex.
    • Added null checks for metrics[0] and processedMetric.
    • Applied optional chaining and nullish coalescing for allChartData[allChartData.length - 1]?.distance.
    • Added null checks for activityData and its nested properties.
    • Applied nullish coalescing for activityData.activity!.splits?.lapDTOs.
    • Updated chart formatter functions to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/BodyBatteryCard.tsx
    • Updated chart formatter to handle undefined values and apply nullish coalescing.
  • SparkyFitnessFrontend/src/pages/Reports/ExerciseReportsDashboard.tsx
    • Updated exerciseDashboardData prop type to allow undefined.
    • Applied nullish coalescing for event.activePayload[0]?.payload.entry_date.
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/FastingReport.tsx
    • Defined Zones interface.
    • Added null checks for zones properties before incrementing counts.
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/HRVCard.tsx
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/MeasurementChartsGrid.tsx
    • Updated MeasurementData interface to CheckInMeasurement.
    • Added type assertion for ChartDataPoint[] in getYAxisDomain.
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/MoodChart.tsx
    • Added optional chaining to payload[0]?.payload and null checks for entry.
  • SparkyFitnessFrontend/src/pages/Reports/NutritionChartsGrid.tsx
    • Applied nullish coalescing for getStringColor(cn.name).
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/Reports.tsx
    • Applied nullish coalescing for measurementData prop.
  • SparkyFitnessFrontend/src/pages/Reports/ReportsTables.tsx
    • Updated PersonalRecord interface with oneRM, weight, reps.
    • Updated prData prop type to allow undefined.
    • Added null checks for entries in food data processing.
    • Applied nullish coalescing for sort function arguments.
    • Added optional chaining to prData[entry.exercises.id]?.date.
    • Applied nullish coalescing for new Date(b.timestamp || 0) and new Date(a.timestamp || 0).
    • Added null checks for measurement.timestamp.
  • SparkyFitnessFrontend/src/pages/Reports/RespirationCard.tsx
    • Updated chart formatter to handle undefined values and apply nullish coalescing.
  • SparkyFitnessFrontend/src/pages/Reports/SleepAnalyticsCharts.tsx
    • Applied nullish coalescing for new Date(data.earliestBedtime || 0) and latestWakeTime.
    • Updated chart formatter to handle undefined values and apply nullish coalescing.
  • SparkyFitnessFrontend/src/pages/Reports/SleepHeartRateCard.tsx
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/SleepRespirationCard.tsx
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/SleepScience/EnergySchedule.tsx
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/SleepScience/SleepDebtHistory.tsx
    • Updated DEBT_COLORS type and added null checks/default color in getBarColor.
    • Updated chart formatter to handle undefined values and apply nullish coalescing.
  • SparkyFitnessFrontend/src/pages/Reports/SleepScience/SleepNeedBreakdown.tsx
    • Updated chart formatter to handle undefined values and apply nullish coalescing.
  • SparkyFitnessFrontend/src/pages/Reports/SleepStageChart.tsx
    • Added null checks for segmentStageType, current, next, and stageTypeLabel.
    • Added type assertion for SLEEP_STAGE_COLORS key.
  • SparkyFitnessFrontend/src/pages/Reports/SpO2Card.tsx
    • Updated chart formatter to handle undefined values.
  • SparkyFitnessFrontend/src/pages/Reports/WorkoutReportVisualizer.tsx
    • Applied nullish coalescing for today in prProgressionData.
  • SparkyFitnessFrontend/src/pages/Settings/AIServiceSettings.tsx
    • Changed null to empty string '' for custom_url and model_name defaults.
  • SparkyFitnessFrontend/src/pages/Settings/AccountSecurity.tsx
    • Added optional chaining to user.email.
  • SparkyFitnessFrontend/src/pages/Settings/AddExternalProviderForm.tsx
    • Added optional chaining to connectionHandlers[createdProvider.provider_type].
  • SparkyFitnessFrontend/src/pages/Settings/CustomCategoryManager.tsx
    • Added optional chaining to user.activeUserId in various hooks.
  • SparkyFitnessFrontend/src/pages/Settings/ExternalProviderList.tsx
    • Added optional chaining to user.activeUserId.
    • Changed null to empty string '' for various _last_sync_at and _token_expires fields.
    • Changed null to undefined for sync_frequency.
  • SparkyFitnessFrontend/src/pages/Settings/ExternalProviderSettings.tsx
    • Added optional chaining to user.activeUserId.
  • SparkyFitnessFrontend/src/pages/Settings/FamilyAccessManager.tsx
    • Added optional chaining to user.activeUserId.
    • Applied nullish coalescing for access.access_end_date.split('T')[0].
  • SparkyFitnessFrontend/src/pages/Settings/GarminConnectSettings.tsx
    • Added null check for result.client_state before setting garminClientState.
  • SparkyFitnessFrontend/src/pages/Settings/NutrientDisplaySettings.tsx
    • Added null check for newPrefsAtIndex before spreading properties.
  • SparkyFitnessFrontend/src/pages/Settings/ProfileFormContent.tsx
    • Applied nullish coalescing for user?.id.
    • Added optional chaining to user.id.
  • SparkyFitnessFrontend/src/pages/Settings/ProfileInformation.tsx
    • Added non-null assertion to user.activeUserId.
  • SparkyFitnessFrontend/src/pages/Settings/WaterContainerManager.tsx
    • Added optional chaining to user.activeUserId.
  • SparkyFitnessFrontend/src/tests/components/AIServiceSettings.test.tsx
    • Updated property access for defaultValueOrOpts['defaultValue'].
    • Removed id from newService object in test data.
  • SparkyFitnessFrontend/src/tests/components/MealBuilder.test.tsx
    • Updated property access for defaultValueOrOpts['defaultValue'].
  • SparkyFitnessFrontend/src/tests/components/MealManagement.test.tsx
    • Updated property access for defaultValueOrOpts['deefaultValue'] (note: original typo retained).
  • SparkyFitnessFrontend/src/tests/components/MealPlanCalendar.test.tsx
    • Updated property access for defaultValueOrOpts['defaultValue'].
  • SparkyFitnessFrontend/src/tests/services/aiServiceSettingsService.test.ts
    • Updated expectation for getPreferences to return an object instead of null.
  • SparkyFitnessFrontend/src/tests/services/stressDataParser.test.ts
    • Added optional chaining to access stress_level in test assertions.
  • SparkyFitnessFrontend/src/tests/utils/calorieCalculations.test.ts
    • Updated property access for ACTIVITY_MULTIPLIERS keys.
  • SparkyFitnessFrontend/src/types.ts
    • Updated SLEEP_STAGE_COLORS type to a plain object.
  • SparkyFitnessFrontend/src/types/diary.ts
    • Updated Goals interface to allow number | undefined for custom nutrients.
  • SparkyFitnessFrontend/src/types/onboarding.ts
    • Created new file to define OnboardingData and Sex interfaces.
  • SparkyFitnessFrontend/src/types/reports.ts
    • Imported PersonalRecordsMap.
    • Expanded DailyFoodEntry interface with explicit optional nutrient properties.
    • Updated prData type in ExerciseDashboardData to PersonalRecordsMap.
  • SparkyFitnessFrontend/src/utils/Chatbot_utils.ts
    • Updated property access for data['intent'].
  • SparkyFitnessFrontend/src/utils/api.ts
    • Updated property access for (error as Record<string, unknown>)['message'].
  • SparkyFitnessFrontend/src/utils/chartUtils.ts
    • Added null check for value before multiplication in calculateSmartYAxisDomain.
  • SparkyFitnessFrontend/src/utils/foodSearch.ts
    • Updated conditional logic for shouldScale and serving_quantity.
    • Changed id: undefined to id: '' for new Food objects.
    • Added null checks for nutrient.nutrientName.
    • Applied nullish coalescing for serving_size and serving_unit.
    • Changed brand to default to an empty string.
  • SparkyFitnessFrontend/src/utils/nutritionCalculations.ts
    • Updated meals parameter type to allow undefined.
    • Applied optional chaining and nullish coalescing for dietTemplate percentages.
  • SparkyFitnessFrontend/src/utils/onboarding.ts
    • Updated FormData type to OnboardingData.
  • SparkyFitnessFrontend/src/utils/reportUtil.ts
    • Defined NutrientTotals interface.
    • Added null checks for splitStartDate and splitEndDate.
    • Updated calculateFoodDayTotal return type.
    • Added null checks for entries in exportFoodDiary.
    • Added optional chaining to entry.foods properties.
    • Applied nullish coalescing for totals and timestamp values.
    • Added null checks for measurement.timestamp.
  • SparkyFitnessFrontend/ts.txt
    • Removed file.
  • SparkyFitnessFrontend/tsconfig.app.json
    • Enabled strict mode.
    • Removed several specific strictness rules that are now covered by strict: true.
    • Added noUncheckedIndexedAccess and noPropertyAccessFromIndexSignature.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@Sim-sat
Copy link
Contributor Author

Sim-sat commented Mar 6, 2026

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces significant improvements to type safety by enabling stricter TypeScript compiler options. The changes are extensive and mostly correct in handling potential null and undefined values. However, I've identified several issues, including a few critical bugs that could lead to incorrect calculations and runtime errors. Specifically, there's an operator precedence issue in a calorie calculation, a syntax error in a component, and a few places where API calls could be made with undefined parameters. I've also noted a regression in type safety in the central apiCall function. Please review the detailed comments for each issue.

Note: Security Review did not run due to the size of the PR.

@Sim-sat Sim-sat marked this pull request as ready for review March 6, 2026 15:12
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request enables strict null checks and other related TypeScript rules, which is a significant step towards improving code safety. The changes are extensive, touching many files to add null checks, optional chaining, and type assertions. While most changes are correct and improve null safety, I've identified several critical issues that need to be addressed. These include a bug in calorie calculation, incorrect error handling logic, potential for creating invalid API requests with undefined IDs, and a significant weakening of type safety in the generic apiCall function. Please review the detailed comments for each issue.

Note: Security Review is unavailable for this PR.

I am having trouble creating individual review comments. Click here to see my feedback.

SparkyFitnessFrontend/src/api/Chatbot/Chatbot_FoodHandler.ts (505)

critical

There's a logical error here due to operator precedence. The expression quantity ?? 0 / (selectedOption.serving_size || 100) is evaluated as quantity ?? (0 / (selectedOption.serving_size || 100)), which simplifies to quantity ?? 0. This means the division by serving_size is completely lost, and the calculation will be incorrect. You should wrap quantity ?? 0 in parentheses to ensure the division happens correctly.

        ((quantity ?? 0) / (selectedOption.serving_size || 100))

SparkyFitnessFrontend/src/api/api.ts (19-23)

critical

Changing apiCall to no longer be generic and return Promise<any> significantly weakens the type safety across the entire application, which contradicts the goal of this PR. This change means that callers of apiCall will lose all type information for the response data. Please revert this to use generics (async function apiCall<T>(...): Promise<T>) to maintain type safety. You can then handle the type assertions within the function where needed, for example by using [] as unknown as T for specific cases where you return an empty array.

export async function apiCall<T = any>(
  endpoint: string,
  options?: ApiCallOptions
): Promise<T> {

SparkyFitnessFrontend/src/components/Onboarding/PersonalPlanHeader.tsx (101-103)

critical

There appears to be a syntax error here with a misplaced closing parenthesis. This will cause a rendering issue.

            {plan?.bmr &&
              Math.round(convertEnergy(plan.bmr, 'kcal', localEnergyUnit))}
            {getEnergyUnitString(localEnergyUnit)}

SparkyFitnessFrontend/src/api/Chatbot/Chatbot_MeasurementHandler.ts (191)

high

Initializing categorySearchError with an empty object {} is problematic. The subsequent check if (categorySearchError && ...) will always evaluate the first part as true, even when no error has been caught. This changes the control flow of your application. To fix this while adhering to strict null checks, you should initialize it with null and type it as ApiError | null, or use undefined and type it as ApiError | undefined.

        let categorySearchError: ApiError | null = null;

SparkyFitnessFrontend/src/api/Foods/mealPlanTemplate.ts (32)

high

The templateData.id could be undefined because templateData is a Partial<MealPlanTemplate>. This would result in an API call to /meal-plan-templates/undefined, which is likely an error. You should add a check to ensure templateData.id exists before making the API call, or adjust the function signature to enforce it.

SparkyFitnessFrontend/src/api/Foods/meals.ts (34-35)

high

The mealId parameter is now optional, but if it's undefined, the API call will be made to /meals/undefined, which will likely result in an error. You should add a check to ensure mealId is not undefined before making the call, or handle this case appropriately (e.g., by disabling the query if mealId is not present).

export const getMealById = async (mealId: string): Promise<Meal> => {
  return await apiCall(`/meals/${mealId}`, { method: 'GET' });

SparkyFitnessFrontend/src/pages/Reports/FastingReport.tsx (97-100)

high

The logic for calculating zoneData seems to have a bug. The condition && zones.Anabolic (and similar for other zones) will be false when the count is 0, preventing the count from ever being incremented. You should remove these checks to correctly count the fasts in each zone.

      if (hrs < 12) zones.Anabolic += 1;
      else if (hrs < 16) zones.Catabolic += 1;
      else if (hrs < 20) zones.FatBurning += 1;
      else zones.Ketosis += 1;

SparkyFitnessFrontend/src/tests/components/MealManagement.test.tsx (26)

high

There is a typo here. It should be defaultValue instead of deefaultValue. This will cause tests to fail or behave unexpectedly.

        return defaultValueOrOpts['defaultValue'] as string;

@Sim-sat Sim-sat force-pushed the strict-null-checks branch from e2f3b4e to 006ef2c Compare March 6, 2026 20:03
@Sim-sat Sim-sat force-pushed the strict-null-checks branch from 006ef2c to c549305 Compare March 6, 2026 20:08
@CodeWithCJ CodeWithCJ merged commit 94dbf12 into CodeWithCJ:main Mar 6, 2026
6 checks passed
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.

2 participants