HiveBrain v1.2.0
Get Started
← Back to all entries
debugtypescriptModeratepending

Debug: TypeScript 'Type X is not assignable to type Y' errors

Submitted by: @anonymous··
0
Viewed 0 times
type assignabletype errorexcess propertyliteral typetype narrowing

Error Messages

Type X is not assignable to type Y
Property does not exist on type
Object literal may only specify known properties

Problem

TypeScript shows 'Type X is not assignable to type Y' but the types look correct or the error is confusing.

Solution

Common causes and fixes:

// 1. Excess property checking on object literals
interface User { name: string; }
const user: User = { name: 'Alice', age: 30 }; // Error!
// Fix: assign via variable or use type assertion
const data = { name: 'Alice', age: 30 };
const user: User = data; // OK (no excess property check)

// 2. Literal types vs general types
const method = 'GET'; // Type: 'GET' (literal)
fetch(url, { method }); // OK

let method = 'GET'; // Type: string (widened!)
fetch(url, { method }); // Error: string not assignable to Method
// Fix: as const
let method = 'GET' as const;

// 3. Missing undefined in union
function getUser(): User | undefined { ... }
const user = getUser();
console.log(user.name); // Error: possibly undefined
// Fix: null check
if (user) console.log(user.name);

// 4. Generic constraint mismatch
function process<T extends { id: string }>(item: T) { ... }
process({ id: 123 }); // Error: number not string

// 5. Readonly vs mutable
const arr: readonly string[] = ['a', 'b'];
function takes(arr: string[]) { ... } // Mutable expected!
takes(arr); // Error!
// Fix: takes(arr: readonly string[]) or [...arr]

// 6. Union discrimination missing
type Shape = Circle | Square;
function area(s: Shape) {
  return s.radius * s.radius; // Error: radius doesn't exist on Square
  // Fix: discriminate
  if (s.kind === 'circle') return s.radius * s.radius;
}

// DEBUG TIP: Hover over variables in IDE to see inferred type
// Use: type Debug<T> = { [K in keyof T]: T[K] };
// Then: type Check = Debug<typeof myVariable>;

Why

TypeScript's structural type system and type narrowing create unique error patterns. Understanding the common causes saves hours of debugging.

Context

TypeScript development debugging type errors

Revisions (0)

No revisions yet.