Question presented to candidate:
"What is a generic constraint? Write a function that only accepts things with a length, and a getProperty(obj, key) that rejects keys the object does not have."
What a strong answer should cover:
T extends Xsets an upper bound:Tcan beXor any subtype of it, and inside the function you may use the membersXguarantees- Without a constraint,
x.lengthon aTis an error; withT extends { length: number }it is allowed, and the caller type (string, array) is still preserved in the return - Constraints can refer to other type parameters:
K extends keyof T, returningT[K] - Why a constraint beats a plain parameter type:
(x: HasId) => HasIdforgets extra fields,<T extends HasId>(x: T) => Tkeeps them - The classic error: returning
{ id: 0 }asTfails becauseT"could be instantiated with a different subtype of constraint" - Variants:
T extends object, unions (T extends string | number), intersections for several requirements, constructor types (new () => T)
Code / implementation expected: Yes β a longest or getProperty with a constraint, and the error it prevents.