> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nativedesktop.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Type Checking

> Check TypeScript types in your Native Desktop project

The `types` command runs TypeScript's type checker on your Native Desktop project to validate type safety, catch type errors, and ensure your code adheres to TypeScript's type system without emitting any output files.

## Prerequisites

Before running the types command, ensure:

* Your project has been created using `native-desktop create`
* All dependencies are installed (`npm install`)
* TypeScript configuration exists (`tsconfig.json`)
* Your project uses TypeScript (`.ts` or `.tsx` files)

## Basic Usage

To check TypeScript types in your project, open the terminal in the **root directory** of your Native Desktop project and run:

```shellscript theme={null}
native-desktop types
```

This command will:

1. Load TypeScript configuration from `tsconfig.json`
2. Analyze all TypeScript files in your project
3. Check for type errors and inconsistencies
4. Report any type-related issues
5. Exit with an appropriate status code

## What Gets Checked

By default, the types command checks:

* All TypeScript files (`.ts`, `.tsx`)
* Type definitions (`.d.ts` files)
* Files in the `src/` directory
* Files specified in `tsconfig.json` include patterns

Files and directories specified in `tsconfig.json` exclude patterns are automatically skipped.

## Output Examples

### Successful Type Check (No Errors)

```shellscript theme={null}
$ native-desktop types

✓ Type checking complete
✓ No type errors found
All TypeScript types are valid
```

### With Type Errors

```shellscript theme={null}
$ native-desktop types

✖ Type checking failed: 3 errors found

src/components/Button.tsx:15:7
  Type 'string' is not assignable to type 'number'.
  15   const count: number = "hello";
           ~~~~~

src/utils/helpers.ts:23:16
  Property 'name' does not exist on type 'User'.
  23   return user.name;
                  ~~~~

src/index.ts:45:10
  Argument of type 'boolean' is not assignable to parameter of type 'string'.
  45   myFunction(true);
          ~~~~

✖ Found 3 type errors
```

### With Warnings

```shellscript theme={null}
$ native-desktop types

⚠ Type checking complete with warnings

src/models/User.ts:12:5
  'age' is declared but its value is never read.
  12   age: number;
       ~~~

✓ 0 errors, 1 warning
```

## TypeScript Configuration

The types command uses the `tsconfig.json` file generated by `native-desktop create`. Here's an example configuration:

```json theme={null}
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "lib": ["ES2022"],
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "bin", "dist"]
}
```

## TypeScript Compiler Options

Common compiler options that affect type checking:

<Tabs>
  <Tab title="Strict Checks">
    * **strict**: Enable all strict type-checking options
    * **noImplicitAny**: Error on expressions with implied `any` type
    * **strictNullChecks**: Enable strict null checking
    * **strictFunctionTypes**: Enable strict checking of function types
    * **strictBindCallApply**: Enable strict checking of `bind`, `call`, and `apply`
    * **strictPropertyInitialization**: Ensure class properties are initialized
  </Tab>

  <Tab title="Error Detection">
    * **noUnusedLocals**: Report errors on unused local variables
    * **noUnusedParameters**: Report errors on unused parameters
    * **noImplicitReturns**: Report error when function doesn't return value
    * **noFallthroughCasesInSwitch**: Report errors for fallthrough cases in switch
    * **noUncheckedIndexedAccess**: Add `undefined` to unverified index signatures
  </Tab>

  <Tab title="Module Resolution">
    * **moduleResolution**: Specify module resolution strategy (`node`, `classic`)
    * **esModuleInterop**: Enable interoperability between CommonJS and ES Modules
    * **resolveJsonModule**: Allow importing JSON files
    * **allowSyntheticDefaultImports**: Allow default imports from modules with no default export
  </Tab>

  <Tab title="Other Options">
    * **noEmit**: Do not emit output files (only check types)
    * **skipLibCheck**: Skip type checking of declaration files
    * **forceConsistentCasingInFileNames**: Ensure consistent casing in imports
    * **isolatedModules**: Ensure each file can be safely transpiled
  </Tab>
</Tabs>

## Common Type Errors

<AccordionGroup>
  <Accordion title="Type Mismatch">
    **Error**: `Type 'X' is not assignable to type 'Y'`

    **Cause**: You're trying to assign a value of one type to a variable of another type.

    **Solution**: Ensure the types match or use type assertions/conversions.

    ```typescript theme={null}
    // ❌ Error
    const count: number = "hello";

    // ✅ Fixed
    const count: number = 42;
    ```
  </Accordion>

  <Accordion title="Property Does Not Exist">
    **Error**: `Property 'X' does not exist on type 'Y'`

    **Cause**: You're accessing a property that doesn't exist on the object's type.

    **Solution**: Add the property to the type definition or use optional chaining.

    ```typescript theme={null}
    // ❌ Error
    interface User {
      name: string;
    }
    const user: User = { name: "John" };
    console.log(user.age);

    // ✅ Fixed
    interface User {
      name: string;
      age?: number;
    }
    const user: User = { name: "John" };
    console.log(user.age);
    ```
  </Accordion>

  <Accordion title="Implicit Any">
    **Error**: `Parameter 'X' implicitly has an 'any' type`

    **Cause**: TypeScript can't infer the type and no explicit type is provided.

    **Solution**: Add explicit type annotations.

    ```typescript theme={null}
    // ❌ Error
    function greet(name) {
      return `Hello, ${name}`;
    }

    // ✅ Fixed
    function greet(name: string): string {
      return `Hello, ${name}`;
    }
    ```
  </Accordion>

  <Accordion title="Null or Undefined Error">
    **Error**: `Object is possibly 'null' or 'undefined'`

    **Cause**: You're accessing a property on a value that might be null or undefined.

    **Solution**: Add null checks or use optional chaining.

    ```typescript theme={null}
    // ❌ Error
    function getLength(text: string | null) {
      return text.length;
    }

    // ✅ Fixed
    function getLength(text: string | null) {
      return text?.length ?? 0;
    }
    ```
  </Accordion>

  <Accordion title="Missing Return Statement">
    **Error**: `Function lacks ending return statement`

    **Cause**: A function with a non-void return type doesn't return a value in all code paths.

    **Solution**: Ensure all code paths return a value.

    ```typescript theme={null}
    // ❌ Error
    function getValue(flag: boolean): number {
      if (flag) {
        return 42;
      }
      // Missing return for else case
    }

    // ✅ Fixed
    function getValue(flag: boolean): number {
      if (flag) {
        return 42;
      }
      return 0;
    }
    ```
  </Accordion>
</AccordionGroup>

## Integration with Development Workflow

### Pre-Commit Hook

Add type checking to your pre-commit hooks:

```json theme={null}
{
  "husky": {
    "hooks": {
      "pre-commit": "native-desktop types && native-desktop lint"
    }
  }
}
```

### CI/CD Pipeline

Include type checking in your continuous integration:

```yaml theme={null}
# GitHub Actions example
- name: Type Check
  run: native-desktop types
```

### npm Scripts

Add type checking to your package.json scripts:

```json theme={null}
{
  "scripts": {
    "typecheck": "native-desktop types",
    "test": "native-desktop types && npm run test:unit",
    "validate": "native-desktop types && native-desktop lint && native-desktop fmt"
  }
}
```

## Exit Codes

The types command uses standard exit codes for CI/CD integration:

* **0**: No type errors found
* **1**: Type errors found

```shellscript theme={null}
native-desktop types
echo $?  # Check exit code
```

## Common Issues

<AccordionGroup>
  <Accordion title="TypeScript Configuration Not Found">
    **Error**: `Cannot find tsconfig.json`

    **Solution**: Ensure the configuration file exists in your project root.

    ```shellscript theme={null}
    # Check if file exists
    ls -la tsconfig.json

    # If missing, create a basic configuration
    npx tsc --init
    ```
  </Accordion>

  <Accordion title="Cannot Find Module">
    **Error**: `Cannot find module 'xyz'`

    **Solution**: Install missing type definitions or dependencies.

    ```shellscript theme={null}
    # Install missing types
    npm install --save-dev @types/node

    # Or install the actual package
    npm install xyz
    ```
  </Accordion>

  <Accordion title="Too Many Type Errors">
    **Error**: Overwhelmed by type errors in a new project

    **Solution**: Fix errors gradually or adjust strictness settings temporarily.

    ```json theme={null}
    {
      "compilerOptions": {
        "strict": false,  // Temporarily disable strict mode
        "noImplicitAny": false
      }
    }
    ```
  </Accordion>

  <Accordion title="Type Definitions Conflict">
    **Error**: Conflicting type definitions

    **Solution**: Check for duplicate type packages or version mismatches.

    ```shellscript theme={null}
    # List installed type packages
    npm list @types

    # Remove duplicates
    npm uninstall @types/xyz
    npm install --save-dev @types/xyz@latest
    ```
  </Accordion>

  <Accordion title="Out of Memory Error">
    **Error**: `JavaScript heap out of memory`

    **Solution**: Increase Node.js memory limit or exclude large directories.

    ```shellscript theme={null}
    # Increase memory limit
    NODE_OPTIONS="--max-old-space-size=4096" native-desktop types
    ```

    Update `tsconfig.json`:

    ```json theme={null}
    {
      "exclude": ["node_modules", "bin", "dist", "large-folder"]
    }
    ```
  </Accordion>
</AccordionGroup>

## Customizing Type Checking

You can customize TypeScript's behavior in `tsconfig.json`:

```json theme={null}
{
  "compilerOptions": {
    // Enable strict type checking
    "strict": true,
    
    // Report errors for unused variables
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    
    // Require explicit return types
    "noImplicitReturns": true,
    
    // Check indexed access
    "noUncheckedIndexedAccess": true,
    
    // Skip checking of declaration files
    "skipLibCheck": true,
    
    // Do not emit output
    "noEmit": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}
```

## IDE Integration

Most modern IDEs provide built-in TypeScript support:

### Visual Studio Code

TypeScript support is built-in. Configure in `settings.json`:

```json theme={null}
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "typescript.updateImportsOnFileMove.enabled": "always",
  "editor.codeActionsOnSave": {
    "source.organizeImports": true
  }
}
```

### WebStorm / IntelliJ IDEA

TypeScript support is built-in and enabled by default.

**Settings → Languages & Frameworks → TypeScript**

* Enable TypeScript Language Service
* Use project's TypeScript version

## Type Checking Specific Files

While the CLI command checks the entire project, you can check specific files using tsc directly:

```shellscript theme={null}
# Check specific file
npx tsc --noEmit src/index.ts

# Check specific directory
npx tsc --noEmit src/components/*.ts

# Check with different config
npx tsc --noEmit -p tsconfig.production.json
```

## Watch Mode

For continuous type checking during development, use TypeScript's watch mode:

```shellscript theme={null}
# Run TypeScript compiler in watch mode
npx tsc --noEmit --watch
```

This will continuously check types as you make changes to your code.

## Best Practices

<CardGroup cols={2}>
  <Card title="Enable Strict Mode" icon="shield">
    Use `"strict": true` for maximum type safety and error prevention.
  </Card>

  <Card title="Type Everything" icon="tags">
    Add explicit type annotations, especially for function parameters and return types.
  </Card>

  <Card title="Check Regularly" icon="clock">
    Run type checking frequently during development to catch errors early.
  </Card>

  <Card title="Fix Incrementally" icon="stairs">
    When facing many errors, fix them incrementally rather than all at once.
  </Card>
</CardGroup>

## Type Safety Levels

Different levels of type strictness you can configure:

<Tabs>
  <Tab title="Relaxed (Not Recommended)">
    ```json theme={null}
    {
      "compilerOptions": {
        "strict": false,
        "noImplicitAny": false,
        "skipLibCheck": true
      }
    }
    ```

    Easy to start, but provides minimal type safety.
  </Tab>

  <Tab title="Standard">
    ```json theme={null}
    {
      "compilerOptions": {
        "strict": true,
        "skipLibCheck": true
      }
    }
    ```

    Good balance between safety and ease of use.
  </Tab>

  <Tab title="Strict (Recommended)">
    ```json theme={null}
    {
      "compilerOptions": {
        "strict": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true
      }
    }
    ```

    Maximum type safety with comprehensive error checking.
  </Tab>
</Tabs>

## Command Comparison

| Command                | Purpose                | Auto-Fix   | Type Checking |
| ---------------------- | ---------------------- | ---------- | ------------- |
| `native-desktop types` | Check TypeScript types | ❌ No       | ✅ Yes         |
| `native-desktop lint`  | Check code quality     | ⚠️ Limited | ❌ No          |
| `native-desktop fmt`   | Format code style      | ✅ Yes      | ❌ No          |

<Info>
  Use all three commands together for comprehensive code quality: types for type safety, lint for code quality, and fmt for consistent formatting.
</Info>

## Development Workflow

Recommended workflow for type-safe development:

```mermaid theme={null}
graph LR
    A[Write Code] --> B[Save File]
    B --> C[IDE Type Check]
    C --> D{Type Errors?}
    D -->|Yes| E[Fix Types]
    D -->|No| F[Continue]
    E --> A
    F --> G[Before Commit]
    G --> H[native-desktop types]
    H --> I{Pass?}
    I -->|No| E
    I -->|Yes| J[Commit]
```

## Performance Optimization

For large projects, optimize type checking performance:

```json theme={null}
{
  "compilerOptions": {
    // Skip checking declaration files
    "skipLibCheck": true,
    
    // Use incremental compilation
    "incremental": true,
    
    // Specify output for incremental info
    "tsBuildInfoFile": ".tsbuildinfo"
  },
  "exclude": [
    "node_modules",
    "bin",
    "dist",
    "**/*.spec.ts"
  ]
}
```
