Q21: What is the `keyof` operator and how is it used?
The keyof operator produces a union of string or numeric literal types representing the key names of an object type.
keyof Operator Usage
interface User {
id: number;
name: string;
email: string;
}
type UserKeys = keyof User; // Type: 'id' | 'name' | 'email'
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}💡 K extends keyof T guarantees that the provided key argument exists on the target object type T.
Key Takeaways
keyof Treturns a union of all property name keys belonging to typeT.