tezvyn:

Create a generic getProperty using generics and keyof

AI-drafted, machine-checkedSource: typescriptlang.orgadvanced

Whether you can constrain a generic key with keyof and return the exact property type. Use T for the object and K extends keyof T for the key, returning T[K].

RED FLAG

Using string for the key allows invalid properties and erases the return type.

WHAT THIS TESTS: This question probes your fluency with TypeScript's type system at the level of generic constraints and indexed access types. The interviewer wants to see if you understand how to traffic type information from an object through to a key parameter and back out through the return type, ensuring compile-time safety without resorting to any.

A GOOD ANSWER COVERS: First, introduce a generic type parameter T to represent the object. Second, introduce a second generic K that is constrained with extends keyof T so that K can only be a key that actually exists on T. Third, set the return type to T[K] so that the function returns the exact type of the property being accessed, not a widened type like any or unknown. Fourth, mention that this pattern lets the compiler catch invalid keys at compile time and enables autocomplete in the IDE.

COMMON WRONG ANSWERS: A red flag is typing the key parameter as string or any, which removes all compile-time guarantees and allows invalid property names to slip through. Another mistake is using only one generic for the object and typing the key as string while casting the return value, which erases the specific property type. Some candidates also forget to constrain K with extends keyof T and instead try to use a union of strings manually, which is brittle and not reusable across different object types.

LIKELY FOLLOW-UPS: The interviewer might ask how you would handle optional properties, which would lead to discussing that T[K] when K is an optional key produces a type that includes undefined. They might also ask about readonly objects or how to write a setProperty counterpart, which requires similar generics but with assignment constraints. Another follow-up is distinguishing between keyof and Object.keys at runtime, since keyof operates on the static type system while Object.keys returns strings.

ONE CONCRETE EXAMPLE: Consider a function defined as function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }. If you have an interface User { name: string; age: number; }, then calling getProperty(user, "name") returns string, getProperty(user, "age") returns number, and getProperty(user, "email") produces a compile-time error because email is not a valid key of User.

Read the original → typescriptlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.