Concept Flow - Keyof operator
Define Interface
Apply keyof Operator
Get Union of Keys
Use Keys as Type
Access Object Properties Safely
The keyof operator takes an object type and produces a union of its keys as string literal types.
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person;
let key: PersonKeys = "name";| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define interface Person with keys 'name' and 'age' | Person = {name: string, age: number} | Interface created |
| 2 | Apply keyof Person | keyof Person | "name" | "age" (union type) |
| 3 | Declare variable key of type PersonKeys | key: "name" | "age" | Variable declared |
| 4 | Assign "name" to key | key = "name" | Valid assignment |
| 5 | Try assign "height" to key | key = "height" | Error: Type '"height"' is not assignable to type '"name" | "age"' |
| Variable | Start | After Step 4 | After Step 5 |
|---|---|---|---|
| key | undefined | "name" | Error (invalid assignment) |
keyof operator syntax: keyof Type Produces a union of string literal types representing keys of Type. Used to get valid property names of an object type. Helps ensure safe property access and type checking. Example: type Keys = keyof Person; // "name" | "age"
keyof operator do in TypeScript?keyofkeyof operator takes an object type and produces a union of its keys as string literal types.keyof = union of keys [OK]keyof lists keys, not values or types [OK]keyof with getting valuesPerson using keyof?keyof syntaxkeyof TypeName without parentheses or dot notation.keys keyword. type Keys = Person.keyof; uses invalid dot notation.keyof Type [OK]keyof TypeName without parentheses [OK]Type.keyofkeyof with keystype Car = { make: string; model: string; year: number };
type CarKeys = keyof Car;
let key: CarKeys = 'year';
console.log(key);keyof usageCarKeys is a union of keys: 'make' | 'model' | 'year'. The variable key is assigned the string 'year', which is valid.key, which is 'year'. No errors occur.keyof returns valuestype User = { id: number; name: string };
function getValue(obj: User, key: keyof User) {
return obj.key;
}obj.key. Since key is a variable, dot notation looks for a property literally named 'key'.obj[key] is required to access the dynamic property.obj[key] for dynamic keys [OK]keyof is invalidkeyof? Choose the correct implementation.keyofK must extend keyof T. This restricts keys to valid property names.T[K], the type of the property at key K. Accessing obj[key] returns this value safely.keyof. function getProp<T>(obj: T, key: string): any { return obj.key; } uses string key and dot notation, which is unsafe. function getProp<T>(obj: T, key: keyof T): string { return obj[key]; } fixes key type but wrongly fixes return type to string. function getProp(obj: T, key: K): K { return obj[key]; } lacks constraint on K and returns wrong type.keyof = safe access [OK]K extends keyof T and return T[K] [OK]keyofPass the test and this pattern moves unknown