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:
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:
Implicit
anytyping:
Objects defined without explicit types receive an implicit index signature allowinganyvalue for undefined keysDynamic key access:
When accessing properties with dynamic keys (map[x]wherexis a number), TypeScript can't guarantee the value's typeType safety conflict:
The assignmentmap[x]returnsany, while the variablesrequiresstring
The term "error typed value" refers to:
- Values inferred as
any anybreaks TypeScript's type safety guarantees- The linter flags these as potentially unsafe operations
Solutions
1. Explicit Object Typing (Recommended)
Add a type annotation to declare valid key/value types:
const map: Record<number, string> = {
0.1: 'bar',
};
const x = Math.random();
const s: string = map[x]; // No lint error2. Type Assertion (Use Sparingly)
Assert the value type when you're certain of safety:
const map = {
0.1: 'bar',
};
const x = Math.random();
const s: string = map[x] as string; // Explicit assertionWARNING
Type assertions bypass type checking - only use when certain of value types
3. Optional Chaining with Fallback
Handle potential undefined values safely:
const map: Record<number, string> = {
0.1: 'bar',
};
const x = Math.random();
const s: string = map[x] ?? 'default'; // Provide fallbackAdditional Troubleshooting Steps
If solutions don't resolve the error:
Restart ESLint Server:
In VS Code:Ctrl/Cmd+Shift+P→ "ESLint: Restart ESLint Server"Check Type Definitions:
Verify imported types resolve correctly - missing type definitions can cause implicitanyEnable Strict Mode:
Ensuretsconfig.jsonhas 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.