typescriptheaven.com, in its article discussing Generics, elaborates on 2 scenarios where the keyword "extends" is utilized when defining type parameters.
interface Lengthwise {
length: number;
}
function processingIdentity<Type extends Lengthwise>(arg: Type): Type {
console.log(arg.length);
return arg;
}
function getValue<Type, Key extends keyof Type>(obj: Type, key: Key) {
return obj[key];
}
let y = { p: 1, q: 2, r: 3, s: 4 };
getValue(y, "p");
getValue(y, "z");
// Error: Argument of type '"z"' is not assignable to parameter of type '"p" | "q" | "r" | "s"'.
The use of the "extends" keyword while constraining a generic type makes sense as it ensures that the type should possess the properties and methods of the extended type (see the first instance above). This aligns with the usage of "extends" keyword in OOP inheritance.
However, what prompts the utilization of the "extends" keyword in the second case mentioned above to restrict the generic type parameter "Key" to be a property of the type parameter "Type"? Why not opt for "in" like "in keyof Type," which seems more fitting?
We appreciate your input and feedback!
Note: I acknowledge that "in keyof" is employed when defining mapped types as depicted below.
type Optional<T> = {
[K in keyof T]?: T[K];
};
My query revolves around why not employ the same approach when limiting a generic type parameter to be a property of another type parameter?