Question presented to candidate:
"What do keyof and typeof do in TypeScript? How is TypeScript's typeof different from JavaScript's, and how would you combine them with generics?"
What a strong answer should cover:
keyof Tis a type operator: the union ofT's property names (keyof Useris"id" | "name" | "admin"); it arrived in TypeScript 2.1 with indexed access typestypeof xin a type position captures the static type of an existing value; in a value position it is JavaScript's run-time operator returning a string like"object"keyof typeof objgives the keys of a value without writing a separate type;ReturnType<typeof fn>reuses a function's result type- The generic pattern
<T, K extends keyof T>(obj: T, key: K): T[K]for type-safe property access - Edge cases: index signatures (
keyof { [k: string]: X }isstring | number),keyof (A | B)is only the shared keys,keyofof a class omits private members, andObject.keysreturnsstring[]on purpose - A type name cannot be used with value
typeof(TS2693): types and values live in separate namespaces
Code / implementation expected: Yes β keyof typeof on a config object and a getProperty or pluck helper.