TypeScript Course
TypeScript
/
Advanced

Type Debugging Scenarios

Definition

Interview questions where the candidate is presented with a block of broken TypeScript code containing complex compiler errors, and must debug and fix the type logic.

Explain Like I'm New

The interviewer shares their screen showing a terrifying red underline in VS Code that says: 'Type X is not assignable to type Y. Property Z is missing...'. You have to explain WHY the compiler is angry, and how to appease it.

Real World Example

Fixing the 'Object is of type unknown' error in a `catch(error)` block in modern TypeScript.

Common Use Cases

  • •Evaluating real-world TS experience
  • •Pair programming interviews

Interactive Example

// DEBUGGING SCENARIO: The Object.keys problem
interface Config { theme: string; retries: number; }
const currentConfig: Config = { theme: 'dark', retries: 3 };

function printConfig() {
  // ERROR: Element implicitly has an 'any' type because expression 
  // of type 'string' can't be used to index type 'Config'.
  Object.keys(currentConfig).forEach((key) => {
    // console.log(currentConfig[key]); 
  });

  // FIX 1: Assert the key type
  Object.keys(currentConfig).forEach((key) => {
    const typedKey = key as keyof Config;
    console.log(currentConfig[typedKey]); // Safe!
  });

  // FIX 2 (Better): Write a strongly typed keys utility
  function getKeys<T extends object>(obj: T) { 
    return Object.keys(obj) as Array<keyof T>; 
  }
  
  getKeys(currentConfig).forEach(key => {
    console.log(currentConfig[key]); // Safe and clean!
  });
}

Interview Questions

basic

  • Why does `catch (error)` throw an 'Object is of type unknown' error?

intermediate

  • Why does `Object.keys(user).map(k => user[k])` throw an implicit any error?

advanced

  • How do you debug an 'Excess Property Checking' failure on a passed variable?

Flash Cards

Question

Why does catch(error) complain?

Click to reveal answer
Answer

In JS, you can throw anything (a string, a number). Because TS cannot guarantee an Error object was thrown, it types `error` as `unknown`. You MUST do `if (error instanceof Error) { console.log(error.message) }`.

Question

Why does Object.keys() fail indexing?

Click to reveal answer
Answer

`Object.keys(obj)` deliberately returns `string[]`, not `keyof typeof obj`. Therefore, TS thinks you are using a random string to index a specific object, which is unsafe. You must assert the key: `let k = key as keyof User`.