Skip to content

refactor: replace any types with proper TypeScript types for strict type safety#648

Merged
pethers merged 2 commits into
mainfrom
copilot/replace-any-types-with-typescript-types
Nov 17, 2025
Merged

refactor: replace any types with proper TypeScript types for strict type safety#648
pethers merged 2 commits into
mainfrom
copilot/replace-any-types-with-typescript-types

Conversation

Copilot AI commented Nov 17, 2025

Copy link
Copy Markdown
Contributor

Pull Request Description

Eliminates all any type usage in production code (3 instances) to enforce strict type safety per TypeScript React Agent guidelines and ISMS policy.

Changes:

  • TechnicalImplementationDetails interface: Replaced [key: string]: any with [key: string]: unknown and added missing explicit properties expertiseLevel?: string and developmentEffort?: string that were accessed in SecurityResourcesWidget
  • Type guard functions: Replaced as any assertions with Record<string, unknown> in isSecurityLevelWidgetProps and isCIAImpactSummaryWidgetProps
// Before
const val = value as any; // Use any temporarily for property checking
[key: string]: any; // Allow additional properties

// After
const val = value as Record<string, unknown>;
[key: string]: unknown; // Allow additional properties for extensibility

Result: Zero any types in src/ (excluding tests), improved compile-time safety, better IDE support.

Type of Change

  • 🚀 New Feature/Enhancement
  • 🐛 Bug Fix
  • 📈 Analytics & Visualization
  • 🎨 UI/UX Improvements
  • 🏗️ Infrastructure & Performance
  • 🔄 Code Quality & Refactoring
  • 🔒 Security & Compliance
  • 📝 Documentation
  • 📦 Dependencies Update

Component(s) Modified

  • App Core
  • Dashboard
  • Radar Chart
  • Security Level Widget
  • Business Impact Analysis Widget
  • Compliance Status Widget
  • Cost Estimation Widget
  • Security Summary Widget
  • Value Creation Widget
  • Constants / Data Model
  • Hooks

CIA Impact Area

  • Confidentiality
  • Integrity
  • Availability

Security Level Impact

  • Basic
  • Moderate
  • High
  • Very High

Test Coverage Impact

  • My changes affect low-coverage areas (SecurityLevelWidget, RadarChart, CostEstimation, useCIAOptions)
  • I've added tests to improve coverage
  • N/A - Only modifying high-coverage areas

Testing Performed

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing completed
  • Security validation performed

Screenshots/Examples

N/A - Type system changes only, no runtime behavior modification.

Related Issues

Closes #[issue_number]

Checklist

  • My PR title follows the conventional commit format (e.g., feat: add new feature)
  • Code follows project coding standards
  • Tests are passing
  • Documentation has been updated (if applicable)
  • Security compliance is maintained or improved
  • Changes have been reviewed for performance impact
  • Breaking changes are documented (if any)

Additional Notes

All 1545 tests pass. TypeScript strict mode compilation successful. No runtime behavior changes—purely type system improvements.

Original prompt

This section details on the original issue you should resolve

<issue_title>🔒 Replace 'any' types with proper TypeScript types for strict type safety</issue_title>
<issue_description>## 🤖 Recommended Agent: @typescript-react-agent

This issue is best handled by the TypeScript React Agent - an expert in TypeScript strict typing and type-safe development.

🎯 Objective

Replace all any type usages with proper TypeScript types to achieve strict type safety and eliminate runtime type errors for v1.0 release.

📋 Background

The TypeScript React Agent guidelines explicitly state: "ALWAYS use explicit types and interfaces; avoid any (use unknown if needed)". The codebase currently has 29 instances of any type usage (excluding test files), which reduces type safety and increases risk of runtime errors. Per ISMS Secure Development Policy, strict TypeScript configuration is required for code quality.

📊 Current State (Measured Metrics)

  • Total any type usages: 29 instances across source files (excluding tests)
  • TypeScript strict mode: Currently enabled in tsconfig.json ✅
  • Type safety risk: Medium (affects data layer and service interfaces)
  • Key affected areas:
    • src/types/cia-services.ts:163 - [key: string]: any in interface
    • Service method parameters and return types
    • Event handler types
    • Generic data structures

Example from codebase:

// src/types/cia-services.ts:163
export interface SomeInterface {
  [key: string]: any; // ❌ Allow additional properties - too permissive
}

✅ Acceptance Criteria

  • Zero any types in production code (src/ excluding tests)
  • Replace any with proper types: specific interfaces, union types, or unknown where type is genuinely unknown
  • All replaced types maintain backward compatibility
  • TypeScript strict mode checks pass with no errors
  • All existing tests pass after type improvements
  • Document complex type decisions with JSDoc comments
  • No regression in functionality

🛠️ Implementation Guidance for @typescript-react-agent

Agent-Specific Instructions:

Check reusable types first in src/types/ before creating new types
Use utility types (Pick, Omit, Partial, Record) for type composition
Prefer unknown over any when type is genuinely unknown
Add type guards when narrowing from unknown to specific types
Document decisions with JSDoc for complex type choices

Step 1: Audit All any Usage

# Find all any usages (excluding tests)
grep -rn ": any" src --include="*.ts" --include="*.tsx" | grep -v ".test."

Step 2: Categorize and Replace

Category 1: Index Signatures (High Priority)

// ❌ Before
export interface ComponentData {
  [key: string]: any;
}

// ✅ After: Use specific union type
export interface ComponentData {
  [key: string]: string | number | boolean | SecurityLevel | ComponentMetric;
}

// ✅ Or better: Use Record with specific types
export type ComponentDataMap = Record<string, ComponentValue>;
export type ComponentValue = string | number | boolean | SecurityLevel | ComponentMetric;

Category 2: Function Parameters

// ❌ Before
function processData(data: any) {
  return data.value;
}

// ✅ After: Use unknown with type guard
function processData(data: unknown): string {
  if (isValidData(data)) {
    return data.value;
  }
  throw new Error('Invalid data');
}

// Add type guard
function isValidData(data: unknown): data is { value: string } {
  return typeof data === 'object' && data !== null && 'value' in data;
}

Category 3: Event Handlers

// ❌ Before
const handleClick = (e: any) => {
  console.log(e.target.value);
};

// ✅ After: Use proper React event type
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
  console.log(e.currentTarget.value);
};

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  console.log(e.target.value);
};

Category 4: Generic Data Structures

// ❌ Before
interface ApiResponse {
  data: any;
}

// ✅ After: Use generics
interface ApiResponse<T = unknown> {
  data: T;
}

// Usage
type SecurityMetricsResponse = ApiResponse<SecurityMetrics>;
type ComponentDataResponse = ApiResponse<ComponentData[]>;

Step 3: Leverage Existing Types

Reuse from src/types/:

  • cia.ts - SecurityLevel, CIAComponent types
  • businessImpact.ts - Impact analysis types
  • widgets.ts - Widget-specific types
  • compliance.ts - Compliance framework types
  • componentPropExports.ts - Component prop interfaces

Step 4: Add Type Guards

// src/utils/typeGuards.ts (enhance existing or create)
export function isSecurityLevel(value: unknown): value is SecurityLevel {
  return typeof value === 'string' && 
    ['None', 'Low', 'Moderate', 'High', 'Very High'].includes(value);
}

export function isComponentData(value: unknown): value is ComponentDat...

</details>


> **Custom agent used: typescript-react-agent**
> Expert in TypeScript and React development for CIA Compliance Manager

- Fixes Hack23/cia-compliance-manager#641

<!-- START COPILOT CODING AGENT TIPS -->
---

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more [Copilot coding agent tips](https://gh.io/copilot-coding-agent-tips) in the docs.

…safety

Co-authored-by: pethers <1726836+pethers@users.noreply.github.com>
Copilot AI changed the title [WIP] Replace 'any' types with proper TypeScript types refactor: replace any types with proper TypeScript types for strict type safety Nov 17, 2025
Copilot AI requested a review from pethers November 17, 2025 21:20
@github-actions

Copy link
Copy Markdown
Contributor

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

1 similar comment
@github-actions

Copy link
Copy Markdown
Contributor

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR successfully eliminates all any type usage in production code (3 instances) by replacing them with proper TypeScript types, specifically using Record<string, unknown> and index signatures with unknown type. This aligns with the TypeScript React Agent guidelines requiring strict type safety and avoiding any types.

Key changes:

  • Replaced as any type assertions with Record<string, unknown> in type guard functions for safer type narrowing
  • Changed index signature from [key: string]: any to [key: string]: unknown in TechnicalImplementationDetails interface
  • Added explicit optional properties expertiseLevel and developmentEffort to clarify interface expectations

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/utils/typeGuards.ts Replaced two instances of as any assertions with Record<string, unknown> in type guard functions isSecurityLevelWidgetProps and isCIAImpactSummaryWidgetProps, improving type safety while maintaining runtime property checking functionality
src/types/cia-services.ts Replaced [key: string]: any with [key: string]: unknown in TechnicalImplementationDetails interface and added explicit optional properties expertiseLevel and developmentEffort for better type documentation and extensibility

Comment thread src/types/cia-services.ts
Comment on lines +164 to +165
expertiseLevel?: string; // Expertise level required
developmentEffort?: string; // Development effort estimate

Copilot AI Nov 17, 2025

Copy link

Choose a reason for hiding this comment

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

The new properties expertiseLevel and developmentEffort may cause confusion as they seem to duplicate information already present in the effort object (effort.expertise and effort.development).

Consider:

  1. Documenting the distinction between these properties with JSDoc comments
  2. Or, if they serve the same purpose, consider using the existing effort object properties consistently throughout the codebase

Currently, SecurityResourcesWidget accesses these new properties (lines 522, 527, 548, 553, 574, 579), but the actual service implementation (TechnicalImplementationService.getTechnicalImplementation) doesn't return them - only test mocks do. This suggests either:

  • Future implementation is planned
  • The widget should be using effort.expertise and effort.development instead
Suggested change
expertiseLevel?: string; // Expertise level required
developmentEffort?: string; // Development effort estimate

Copilot uses AI. Check for mistakes.
@pethers

pethers commented Nov 17, 2025

Copy link
Copy Markdown
Member

@copilot apply changes based on the comments in this thread

@pethers
pethers marked this pull request as ready for review November 17, 2025 21:51
@pethers
pethers merged commit fa0fe67 into main Nov 17, 2025
28 checks passed
@pethers
pethers deleted the copilot/replace-any-types-with-typescript-types branch November 17, 2025 21:51
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.

3 participants