TypeScript Master (50 Qs)•Part 1: Basic & Foundational TypeScript (Junior / Entry-Level)
What is the `keyof` operator and Indexed Access types?
junior LevelMost AskedCode ExampleTypeScript
In Simple Words:
keyof T: Produces a union of all property keys of typeT.T[K](Indexed Access): Extracts the type of a specific propertyKon typeT.
typescript
interface User {
id: string;
name: string;
age: number;
}
type UserKeys = keyof User; // "id" | "name" | "age"
type AgeType = User["age"]; // number
// Type-safe property getter
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}