What is the keyof operator in TypeScript, and how is it used?
Instruction: Describe the keyof operator and provide an example of its use.
Context: This question tests the candidate's understanding of the keyof operator and its role in TypeScript's type system.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
keyof T forms a union of the property keys described by T. These may be string literals, numeric literals or symbols, depending on the type. It is a type-level operator, not a function that enumerates an object's runtime keys.
interface User { id: number; name: string; email?: string } function getValue<T, K extends keyof T>(object: T, key: K): T[K] { return object[key]; } const user: User = { id: 1,...