Skip to content

Resolving "Unsafe assignment of an error typed value" in TypeScript

Problem Statement

When working with TypeScript objects that use dynamic keys, you might encounter the linting error:
"Unsafe assignment of an error typed value" (@typescript-eslint/no-unsafe-assignment).

This occurs when:

  • You access object properties using dynamically generated keys
  • TypeScript infers the accessed value as potentially any
  • You assign that value to a strictly typed variable

Example code triggering the error:

typescript
const map = {
  0.1: 'bar',
};

const x = Math.random();
// Error: Unsafe assignment of an error typed value
const s: string = map[x];

Core Issue Explained

The error occurs due to TypeScript's inference rules for object types:

  1. Implicit any typing:
    Objects defined without explicit types receive an implicit index signature allowing any value for undefined keys

  2. Dynamic key access:
    When accessing properties with dynamic keys (map[x] where x is a number), TypeScript can't guarantee the value's type

  3. Type safety conflict:
    The assignment map[x] returns any, while the variable s requires string

The term "error typed value" refers to:

  • Values inferred as any
  • any breaks TypeScript's type safety guarantees
  • The linter flags these as potentially unsafe operations

Solutions

Add a type annotation to declare valid key/value types:

typescript
const map: Record<number, string> = {
  0.1: 'bar',
};

const x = Math.random();
const s: string = map[x];  // No lint error

2. Type Assertion (Use Sparingly)

Assert the value type when you're certain of safety:

typescript
const map = {
  0.1: 'bar',
};

const x = Math.random();
const s: string = map[x] as string;  // Explicit assertion

WARNING

Type assertions bypass type checking - only use when certain of value types

3. Optional Chaining with Fallback

Handle potential undefined values safely:

typescript
const map: Record<number, string> = {
  0.1: 'bar',
};

const x = Math.random();
const s: string = map[x] ?? 'default';  // Provide fallback

Additional Troubleshooting Steps

If solutions don't resolve the error:

  1. Restart ESLint Server:
    In VS Code:
    Ctrl/Cmd+Shift+P → "ESLint: Restart ESLint Server"

  2. Check Type Definitions:
    Verify imported types resolve correctly - missing type definitions can cause implicit any

  3. Enable Strict Mode:
    Ensure tsconfig.json has strict type checks:

    json
    {
      "compilerOptions": {
        "strict": true,
        "noImplicitAny": true
      }
    }

Why This Matters

Addressing this error ensures:

  • Safer type conversions
  • Prevention of runtime errors
  • Better code maintainability
  • Full benefits of TypeScript's type system

By explicitly defining object types and handling dynamic access safely, you eliminate dangerous any types from your codebase.