0
0
Typescriptprogramming~20 mins

Indexed access types in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Indexed Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
A"undefined"
B"number"
C"object"
D"string"
Attempts:
2 left
💡 Hint
Look at the type of the 'name' property in the Person type.
🧠 Conceptual
intermediate
2: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]?
Anumber | string
Bnumber
Cstring
Dnumber | string | boolean
Attempts:
2 left
💡 Hint
Indexed access with a union key produces a union of the property types.
🔧 Debug
advanced
2:00remaining
Why does this indexed access type cause an error?
Consider this code snippet:
type Data = { x: number; y: string };
type Key = 'x' | 'z';
type Value = Data[Key];

What error does this code produce?
ANo error, Value is number | undefined.
BSyntax error: Unexpected token '['.
CType error: Property 'z' does not exist on type 'Data'.
DType error: Type 'Key' is not assignable to type 'string'.
Attempts:
2 left
💡 Hint
Check if all keys in 'Key' exist in 'Data'.
Predict Output
advanced
2: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'];
Astring
Bnumber
C{ theme: string; version: number }
Dunknown
Attempts:
2 left
💡 Hint
Indexed access can be chained to get nested property types.
🚀 Application
expert
3: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?
Afunction getValue<K extends keyof User>(key: K): User[K];
Bfunction getValue(key: string): User[key];
Cfunction getValue<K>(key: K): User[K];
Dfunction getValue(key: keyof User): any;
Attempts:
2 left
💡 Hint
Use a generic constrained to keys of User to get the correct value type.