← Back to debugging

The Challenge: “The Type-Safe Data Fetcher”

The scenario

You have a generic function meant to fetch a specific property from an object. The code works at runtime, but the TypeScript compiler is giving an error because the relationship between the key and the object isn't strictly defined.

The buggy code

1interface User {
2  id: number;
3  name: string;
4  email: string;
5}
6
7// THE BUG: 'key' is just a string, so TS doesn't know 
8// if it actually exists on 'obj'.
9function getProperty<T>(obj: T, key: string) {
10  return obj[key]; 
11  // Error: Element implicitly has an 'any' type because 
12  // expression of type 'string' can't be used to index type 'T'.
13}
14
15const user: User = { id: 1, name: "Alice", email: "alice@example.com" };
16
17const userName = getProperty(user, "name"); 
18const userAge = getProperty(user, "age"); // This should be a TS error, but isn't!

How to fix the types

To fix this, you must use a generic constraint with the keyof operator to link the key directly to the object's type.

The corrected version

1// K must be a valid key of T
2function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
3  return obj[key];
4}
5
6const userName = getProperty(user, "name"); // Type is 'string'
7// @ts-expect-error: "age" is not a key of User
8const userAge = getProperty(user, "age");

3-day prep roadmap

DayFocus areaRecommended practice
Day 1Advanced syntaxPractice utility types like Pick, Omit, and Record. Understand when to use unknown vs any.
Day 2Complex scenariosSolve 3–5 TypeHero challenges or TypeScript-specific problems on CodeSignal.
Day 3Tools & workflowPractice using the VS Code debugger instead of console.log. Rehearse explaining your debugging steps out loud.

Final pro-tip: the “negative” test

In many interviews, you might be asked to write a test that should fail. Use // @ts-expect-error or // @ts-ignore to demonstrate that you know exactly where the compiler should be catching a mistake. This shows a very high level of comfort with the language.