Extracting Object Property Types by Key
What you'll learn: How to use indexed access types with infer to extract specific property types from object types dynamically.
The Core Idea
Sometimes you need to extract the type of a specific property from an object type, but you want to do it inside a conditional type where you don't know the object structure ahead of time. You've already learned indexed access (T[K]), but combining it with infer lets you extract property types conditionally — testing if a property exists and capturing its type in one operation.
Think of it like pattern matching: "If this type is an object with property X, capture X's type; otherwise, do something else."
Basic Property Type Extraction
The fundamental pattern uses infer in an indexed access position:
type GetProperty<T, K extends string> =
T extends { [P in K]: infer V } ? V : never;
type User = {
id: number;
name: string;
email: string;
};
type IdType = GetProperty<User, "id">; // number
type NameType = GetProperty<User, "name">; // string
type AgeType = GetProperty<User, "age">; // never (doesn't exist)
Here, { [P in K]: infer V } checks if T has property K, and if so, captures that property's type as V.
Why This Matters
This pattern is useful when building generic utilities that need to extract types based on string literal keys, especially when the key itself might be a union or when you're working with discriminated unions:
type ExtractByType<T, K extends keyof T, V> =
T extends { [P in K]: infer PropType }
? PropType extends V ? T : never
: never;
type Success = { status: "success"; data: string };
type Error = { status: "error"; message: string };
type Result = Success | Error;
// Extract only the variant where status is "success"
type SuccessOnly = Extract<Result, { status: "success" }>; // Success
Key Takeaway: Combining infer with indexed access types lets you conditionally extract property types by key, enabling type-safe reflection patterns where you test for a property's existence and capture its type simultaneously.