Intermediate LevelJavaScript & TypeScript
What are indexed access types (T[K]) in TypeScript?
❓ Interview Prompt: Explain indexed access types for looking up specific property types on an interface or array.
Indexed Access Types (or Lookup Types) allow looking up the specific type of a property on another type using bracket notation:
Syntax:
type Age = User['age'];
Features:
1
Lookup property types dynamically based on interface keys.
2
Look up union property types using union keys:
User['id' | 'name'].3
Look up array element types using number indexing:
MyArray[number].Code Implementation Example
typescript
interface Order {
id: string;
customer: {
name: string;
address: { city: string; zip: string; };
};
items: { productId: number; quantity: number; }[];
}
// Extract nested address type
type Address = Order['customer']['address']; // { city: string; zip: string; }
// Extract single item element type from array using [number]
type OrderItem = Order['items'][number]; // { productId: number; quantity: number; }💡Extracting deeply nested property types and array item types via indexed access.
🎯 Interview Key Takeaway
Indexed access types (T[K] and Array[number]) extract child property types without creating redundant interfaces.
#TypeScript#Indexed Access#Lookup Types#Intermediate
Back to all JavaScript & TypeScript Questions→