Challenge - 5 Problems
Indexed Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of indexed access type usage
What is the type of
result in the following TypeScript code?Typescript
type Person = { name: string; age: number; };
let personName: Person['name'];
personName = "Alice";
const result = typeof personName;Attempts:
2 left
💡 Hint
Look at the type of the 'name' property in the Person type.
✗ Incorrect
The indexed access type Person['name'] extracts the type of the 'name' property, which is string. So typeof personName is 'string'.
🧠 Conceptual
intermediate2:00remaining
Understanding indexed access types with union keys
Given the type
type Keys = 'a' | 'b'; and type Obj = { a: number; b: string; c: boolean; };, what is the type of Obj[Keys]?Attempts:
2 left
💡 Hint
Indexed access with a union key produces a union of the property types.
✗ Incorrect
Obj[Keys] means the type of properties 'a' or 'b' in Obj, which are number and string, so the result is number | string.
🔧 Debug
advanced2:00remaining
Why does this indexed access type cause an error?
Consider this code snippet:
What error does this code produce?
type Data = { x: number; y: string };
type Key = 'x' | 'z';
type Value = Data[Key];What error does this code produce?
Attempts:
2 left
💡 Hint
Check if all keys in 'Key' exist in 'Data'.
✗ Incorrect
The key 'z' does not exist in Data, so accessing Data['z'] causes a type error.
❓ Predict Output
advanced2:00remaining
Output of nested indexed access types
What is the type of
NestedValue in this code?type Config = { settings: { theme: string; version: number } };
type NestedValue = Config['settings']['version'];Attempts:
2 left
💡 Hint
Indexed access can be chained to get nested property types.
✗ Incorrect
Config['settings'] is { theme: string; version: number }, then accessing ['version'] gives number.
🚀 Application
expert3:00remaining
Using indexed access types to create a type-safe function
Given the type
type User = { id: number; name: string; active: boolean };, which function signature correctly uses indexed access types to accept a key and return the corresponding value type?Attempts:
2 left
💡 Hint
Use a generic constrained to keys of User to get the correct value type.
✗ Incorrect
Option A correctly constrains K to keys of User and returns User[K], ensuring type safety.